给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = [1,2]
输出:[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 temp = null;
ListNode cur = head;
ListNode pre = null;
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
递归
/**
* 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 reverse(ListNode pre, ListNode cur) {
if (cur == null) return pre;
ListNode temp = null;
temp = cur.next;
// 反转
cur.next = pre;
// 与普通的双指针法,只是将赋值操作修改为递归的形式
return reverse(cur,temp);
}
public ListNode reverseList(ListNode head) {
return reverse(null,head);
}
}
本文详细介绍了如何通过双指针法和递归方法实现单链表的反转,并提供了完整的Java代码示例。双指针法通过改变每个节点的next指针指向来完成反转过程;递归方法则利用函数调用栈保存链表节点,达到反转效果。
1156

被折叠的 条评论
为什么被折叠?



