题目描述
Given the head of a singly linked list, reverse the list, and return the reversed list.
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
样例描述
Input: head = [1,2,3,4,5]
Output: [5,4,3,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; }
* }
*/
思路
- 迭代法(双指针法)
维护两个相邻的指针同时往后遍历,每次反转右边指针的指向,让其指向左边的指针,直到右边的指针走到空,最后记得将第一个结点的指针指向空! - 递归法:将接口视为黑箱操作(每次可以反转以head为头结点的,并返回尾结点),不断划分子问题
然后将head.next
结点的指针指向head
,head
指向空,返回尾结点就行
代码
- 迭代之双指针法
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return head;
ListNode p = head, q = head.next;
while (q != null){
//提前存下q的后面结点,因为要反转q的指向
ListNode r = q.next;
//反转
q.next = p;
//两个指针同时向后走
p = q;
q = r;
}
head.next = null;
//返回第一个指针,因为第二个指向空,第一个指向尾结点,也就是逆序后的头结点
return p;
}
}
- 递归法
class Solution {
public ListNode reverseList(ListNode head) {
//空或者只有一个结点
if (head == null || head.next == null) return head;
//反转以head.next为头结点的链表,返回尾结点
ListNode tail = reverseList(head.next);
//head.next为头结点的链表后面的指针都反转了,所以反转head.next的指针
head.next.next = head;
head.next = null;
//返回前面得得尾结点
return tail;
}
}