IncredibleThings

导航

Reverse a Singly LinkedList

Reverse a Singly LinkedList
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

这是面试的时候被问到的一题,还是考察LinkedList的理解,最后如何得到reverse之后的head的。

 

public Class Solution{

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

 

posted on 2015-03-11 04:45  IncredibleThings  阅读(129)  评论(0编辑  收藏  举报