题目描述 输入一个链表,反转链表后,输出链表的所有元素。
思路: 反转链表只需改变链接方向,改变方向时需要将原本指向后一个结点的链接方向指向前一个结点,因此需要记录下三个结点。
AC代码:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode cur = head;
ListNode next = null;
ListNode pre = null;
if ( head == null || head.next == null){
return head;
}
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}