Fork me on GitHub

LeetCode-206:反转链表

本题为LeetCode中第206道题(不是很难,只要数据结构基础可以就行)

反转一个单链表。

示例:

1
2
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:

你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

博主代码如下:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @author RickYinPeng
* @ClassName Y_206_反转链表
* @Description 本题为LeetCode中的第206题
* @date 2018/11/21/12:48
*/
public class Y_206_反转链表 {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
l1.next = l2;
reverseList(l1);
}

public static ListNode reverseList(ListNode head) {
if(head==null){
return null;
}
if(head.next==null){
return head;
}
ListNode first = head;
ListNode Pre = null;
while(first.next!=null){
if(first==head){
ListNode temp = first.next;
first.next = Pre;

Pre = first;
first = temp;
}else {
ListNode temp = first.next;
first.next = Pre;
Pre = first;
first = temp;
}
}
first.next = Pre;
return first;
}

}

今天就不再看别的代码了,因为博主的提交意见战胜了100%的提交,所以不看别的了

image

不过我可以说另外一种思路,凡是这种有关让你倒转的题,都可以使用栈来做,栈的特性先进后出