Leetcode链表相关题目
- 206.反转链表
如下图, 假如我们写的reverseList(head)
方法的功能就是反转成功的结果;
reverseList(head.next)
时如下图
如果reverseList(head.next)此时就已经反转了 1 -> 2 -> 3 -> 4 -> null
, 如果要想成功反转为1 2 3 4 5 null
, 我们只需要解决4.next -> 5, 5.next -> null
, 这样就完成了反转
public class ListNode{
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode reverseNode(ListNode head) {
//if (head == null) return null; // 等同 return head
//if (head.next == null) return head; // 此时就一个节点
if (head == null || head.next == null)
return head;
// 此时的newNode就是节点4, 1 -> 2 -> 3 -> 4 -> null
ListNode newNode = reverseNode(head.next)
// 此时要想办法将4的next指向5; 因为此时head指向5, head.next就指向4, head.next.next指向head即可
// 也就是4.next指向5
head.next.next = head;
head.next = null;
return newNode;
}
}
这样就完成了递归反转链表;
2、迭代的方式- 因为题目中只提供了一个
head
指针, 所以我要想达到反转的效果, 就只能从head着手; - 首先提供一个newHead, 指向null, 我们期待的结果是最后返回的这个newHead指向1 -> 2 -> 3 -> 4 -> 5 -> null
思路
: 先让head指向newHead, 然后newHead指向head, 然后head指向它之前的next
一开始就要使用一个变量tmp来引用这head.next, 不然后面的节点都释放了
public class ListNode{
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode reverseNode(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = null;
while (head != null) {
ListNode tmp = head.next; // tmp先指向head.next
head.next = newHead;
newHead = head;
head = tmp;
}
return newNode;
}
}
终止条件为
head != null