206. Reverse Linked List

Reverse a singly linked list.

click to show more hints.

Hint:

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

 

Subscribe to see which companies asked this question

Hide Tags
 Linked List
 
 
Iteratively:
/**
 * 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 a = head;
        ListNode b = head.next;
        
        while(b!=null)
        {
            ListNode bn = b.next;
            b.next = a;
            a = b;
            b = bn;
        }
        
        head.next = null;
        return a;
    }
}

 

 
Recursively:
 
 
 
 
posted @ 2016-04-13 13:19  新一代的天皇巨星  阅读(112)  评论(0)    收藏  举报