题目描述
输入一个链表,反转链表后,输出新链表的表头。
输入:{1,2,3}
输出:{3,2,1}
输入输出的形式我们不用考虑,主要是实现链表反转的算法。
首先,为什么引入tmp呢,因为当head的next指向newHead的时候,head跟2就断开了。。。所以我们需要一个临时节点tmp。
以上是第一步,tmp指向head.next
第二步,head.next 指向 newHead
第三步,newHead指向head
第四步 ,head指向tmp
然后 tmp指向head.next 进行迭代。。。
最终变成了这个样子:
完成了链表的反转。
我们在整理一下
- tmp -> head.next
- head.next -> newHead
- newHead -> head
- head -> tmp
写代码时,只要把指向 改写成 等号=
就可以了。
tmp = head.next;
head.next = newHead;
newHead = head;
head = tmp;
其他细节部分,应该就比较容易懂了。
/*
* 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 tmp;
ListNode newHead = null;
while (head != null) {
tmp = head.next;
head.next = newHead;
newHead = head;
head = tmp;
}
return newHead;
}
}