|
|
@ -2,11 +2,11 @@ |
|
|
|
链表相关 |
|
|
|
链表相关 |
|
|
|
--- |
|
|
|
--- |
|
|
|
|
|
|
|
|
|
|
|
[06: 从头到尾打印链表](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/) |
|
|
|
[06. 从头到尾打印链表](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/) |
|
|
|
|
|
|
|
|
|
|
|
```java |
|
|
|
```java |
|
|
|
class Solution { |
|
|
|
class Solution { |
|
|
|
public int[] reversePrint(ListNode head) { |
|
|
|
public int[s] reversePrint(ListNode head) { |
|
|
|
ListNode temp = head; |
|
|
|
ListNode temp = head; |
|
|
|
int size = 0; |
|
|
|
int size = 0; |
|
|
|
while (temp != null) { |
|
|
|
while (temp != null) { |
|
|
@ -43,7 +43,7 @@ class Solution { |
|
|
|
} |
|
|
|
} |
|
|
|
``` |
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|
[22:链表中倒数第 k 个节点](https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/) |
|
|
|
[22. 链表中倒数第 k 个节点](https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/) |
|
|
|
|
|
|
|
|
|
|
|
```java |
|
|
|
```java |
|
|
|
class Solution { |
|
|
|
class Solution { |
|
|
@ -78,3 +78,47 @@ class Solution { |
|
|
|
} |
|
|
|
} |
|
|
|
``` |
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
[24. 反转链表](https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
```java |
|
|
|
|
|
|
|
class Solution { |
|
|
|
|
|
|
|
public ListNode reverseList(ListNode head) { |
|
|
|
|
|
|
|
if (head == null || head.next == null) { |
|
|
|
|
|
|
|
return head; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
ListNode h1 = head; |
|
|
|
|
|
|
|
ListNode h2 = head.next; |
|
|
|
|
|
|
|
ListNode h3 = null; |
|
|
|
|
|
|
|
h1.next = null; |
|
|
|
|
|
|
|
while (h2 != null) { |
|
|
|
|
|
|
|
h3 = h2.next; |
|
|
|
|
|
|
|
h2.next = h1; |
|
|
|
|
|
|
|
h1 = h2; |
|
|
|
|
|
|
|
h2 = h3; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
return h1; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
```java |
|
|
|
|
|
|
|
class Solution { |
|
|
|
|
|
|
|
public ListNode reverseList(ListNode head) { |
|
|
|
|
|
|
|
// 递归终止条件是当前为空,或者下一个节点为空 |
|
|
|
|
|
|
|
if (head == null || head.next == null) { |
|
|
|
|
|
|
|
return head; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
// 这里的 h1 就是最后一个节点 |
|
|
|
|
|
|
|
ListNode h1 = reverseList(head.next); |
|
|
|
|
|
|
|
// 如果链表是 1->2->3->4->5,那么此时的 cur 就是 5 |
|
|
|
|
|
|
|
// 而 head 是4,head的 下一个是 5,下下一个是空 |
|
|
|
|
|
|
|
// 所以 head.next.next 就是 5->4 |
|
|
|
|
|
|
|
head.next.next = head; |
|
|
|
|
|
|
|
// 防止链表循环,需要将 head.next 设置为空 |
|
|
|
|
|
|
|
head.next = null; |
|
|
|
|
|
|
|
// 每层递归函数都返回 h1,也就是最后一个节点 |
|
|
|
|
|
|
|
return h1; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|