LeetCode刷题08-链表-206.反转链表
题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
提示:
- 链表中节点的数目范围是 [0, 5000]
- -5000 <= Node.val <= 5000
代码
此算法核心在于反转当前节点与前一节点的同时,不能丢失剩余未反转链表入口地址
方式1(双指针法):
/**
* 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) {
ListNode prevNode = null;
ListNode currNode = head;
ListNode nextNode = null;
while(currNode != null) {
nextNode = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = nextNode;
}
return prevNode;
}
}
方式2(递归1):
/**
* 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) {
ListNode newHead = reverse(null, head);
return newHead;
}
public ListNode reverse(ListNode prev, ListNode curr) {
if(curr == null) {
return prev;
}
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
return reverse(prev, curr);
}
}
方式3(递归2):
/**
* 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) {
return null;
}
// 尾部判空
if(head.next == null) {
return head;
}
// 从第二个节点递归至尾部节点
ListNode last = reverseList(head.next);
// 递归开始返回时,此时head指向倒数第二节点
head.next.next = head;
head.next = null;
return last;
}
}