题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:输入:head = [1,2]
输出:[2,1]
示例 3:输入:head = []
输出:[]提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
做题思路
这个题目可以说是很高频的考题了
这个题目的实现方式有两种一种是双指针法,另一种就是递归法
代码实现
/**
* 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 cur=null;
ListNode pre=head;
while(pre!=null){
ListNode next=pre.next;
pre.next=cur;
cur=pre;
pre=next;
}
return cur;
}
}
/**
* 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) {
return reverse(null,head);
}
public ListNode reverse(ListNode pre,ListNode cur){
if(cur==null){
return pre;
}
ListNode next=cur.next;
cur.next=pre;
return reverse(cur,next);
}
}
740

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



