题目:输入一个链表,反转链表后,输出新链表的表头。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null)
return null;
//分别指向当前节点的前驱和后继
ListNode pre = null;
ListNode next = null;
//当前节点不为空的时候
while(head != null){
next = head.next;//反转节点的前驱和后继(注1)
head.next = pre;
pre = head;//更新“当前”节点
head = next;
}
return pre;
}
}
注1:因为是单链表,所以实际操作是让当前节点从指向next改为指向pre。
笔记:
原理很简单,保持头脑清晰,不要搞错顺序指丢了。