翻转链表

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


代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
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) //传入参数head是反转前的链表头0
return null;
ListNode pre = null; //用于存储当前节点head的前置节点
ListNode next = null; //用于存储当前节点head指向的下一节点
while(head!=null){ //判断是否到达链表末尾,如果当前节点head为null,则代表其前置节点pre节点是尾节点
//pre节点即上次(最后一次)进行while循环操作的“当前head节点”
next = head.next; //先拿到head指向的下一节点1
head.next = pre; //再将head指向其前置节点
pre = head; //把当前节点head作为下一次循环的前置节点
head = next; //把下一节点1当做下次循环的当前节点
// 以上几步的顺序不能变,否则会导致链表断裂: 0<-1 2->3
}
return pre;
}
// 反转前0->1->2->3
// 翻转后0<-1<-2<-3
}

---------------- The End ----------------
0%