-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0206.反转链表.java
94 lines (89 loc) · 1.66 KB
/
0206.反转链表.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* @lc app=leetcode.cn id=206 lang=java
*
* [206] 反转链表
*
* https://leetcode.cn/problems/reverse-linked-list/description/
*
* algorithms
* Easy (73.04%)
* Likes: 2595
* Dislikes: 0
* Total Accepted: 1.1M
* Total Submissions: 1.5M
* Testcase Example: '[1,2,3,4,5]'
*
* 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
*
*
*
*
* 示例 1:
*
*
* 输入:head = [1,2,3,4,5]
* 输出:[5,4,3,2,1]
*
*
* 示例 2:
*
*
* 输入:head = [1,2]
* 输出:[2,1]
*
*
* 示例 3:
*
*
* 输入:head = []
* 输出:[]
*
*
*
*
* 提示:
*
*
* 链表中节点的数目范围是 [0, 5000]
* -5000
*
*
*
*
* 进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
*
*
*
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
// 头插法
ListNode dummy = new ListNode(0);
while (head != null) {
ListNode node = head.next;
head.next = dummy.next;
dummy.next = head;
head = node;
}
return dummy.next;
// 递归
// ListNode last = reverseList(head.next);
// head.next.next = head;
// head.next = null;
// return last;
}
}
// @lc code=end