LeetCode 206. 反转链表
2020-03-02 本文已影响0人
桐桑入梦
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
迭代,思路简单
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) return null;
ListNode pre = head , p = head.next , tmp = null;
pre.next = null; //这里写的时候突然忘了考虑,要仔细一些
while( p != null){
tmp = p.next;
p.next = pre;
pre = p;
p = tmp;
}
return pre;
}
}
递龟,思路简单
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if( head == null || head.next==null ) return head;
ListNode p = head.next;
head.next = null;
return reverse(head,p);
}
private ListNode reverse(ListNode pre,ListNode p){
if(p == null) return pre;
ListNode tmp = p.next;
p.next = pre;
return reverse(p,tmp);
}
}
效果: