Leetcode 第206题:Reverse Linked List

链表问题

1.递归思路

/**
 * 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;
        }

        if(head.next == null){
            return head.next;
        }

        ListNode p = head.next;
        ListNode n = reverseList(p);

        head.next = null;
        p.next = head;
        return n;
    }
}

2.循环思路

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {  

    public ListNode reverseList(ListNode head) { 
        if(head==null || head.next==null){ 
            return head;  
        }

        ListNode pre = head;  
        ListNode p = head.next;  
        pre.next = null;  
        ListNode nxt;  
        while(p!=null) {  
            nxt = p.next;  
            p.next = pre;  
            pre = p;  
            p = nxt;  
        }  
        return pre;  
    }  
}  

版权声明:本文为fanpeihua123原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。