0%

反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

三个指针操作,注意将原链表的head.next置为null,同时注意处理原链表为空的情况.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public ListNode ReverseList(ListNode head) {
if (head==null||head.next == null) {
return head;
}
ListNode pre=head,cur=head.next,next=head.next.next;
head.next=null;//容易忘!
while (true){
cur.next=pre;
pre=cur;
cur=next;
if (cur==null){
break;
}
next=cur.next;
}
return pre;
}