AcWing 专题4. 链表专题
原题链接
简单
作者:
AnrolsP
,
2021-03-28 21:07:48
,
所有人可见
,
阅读 347
206. 反转链表
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) {
//递归法:我们直接来看递归最后一次(只有两个节点)的情况:tail = head
//head.next.next = head;
//head.next = null;
//这样,每一次递归都返回反转链表的头节点。因此最后返回的就是整个链表的头节点
//需要特判只有一个节点
if (head == null || head.next == null)return head;
ListNode tail = reverseList(head.next);
head.next.next = head;
head.next = null;
return tail;
}
}
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 || head.next == null)return head;
ListNode curNode = head;
ListNode nextNode = head.next;
while(nextNode != null){
ListNode temp = nextNode.next;
nextNode.next = curNode;
curNode = nextNode;
nextNode = temp;
}
//最后尾指针要设定
head.next = null;
return curNode;
}
}