题目描述
输入一个链表,反转链表后,输出新链表的表头。
答案
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null||head.next==null){
return head;
}
ListNode post = head.next;
ListNode pre = head;
ListNode listNode = head.next;
while(listNode!=null){
post = listNode.next;
listNode.next = pre;
pre = listNode;
listNode = post;
}
head.next = null;
return pre;
}
}
解析
注意三个指针的移动顺序,这个顺序影响循环的判断,以及对空值的判断。
先移动当前节点和post结点,利用当前节点出界作为循环条件。
最后移动pre,让pre等于链表最后一个结点也就是新头结点。
Comments | NOTHING