首页 > 代码库 > LeetCode 206 Reverse a singly linked list.

LeetCode 206 Reverse a singly linked list.

Reverse a singly linked list.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 递归的办法:

/**
 * 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) return null;
        
        if(head.next==null)return head;
        
        ListNode p=head.next;
        ListNode n=reverseList(p);
        
        head.next=null;
        p.next=head;
        return n;
    }
}

 

非递归,迭代的办法:

if(head == null || head.next == null)
     return head; 
ListNode current =  head.next;
head.next = null;
while(current ! = null){
     ListNode temp = current.next;
     current.next = head;
     head = current;
    current = temp.next;
}
return head;

 

LeetCode 206 Reverse a singly linked list.