leetcode : reverse linked list [基本功,闭着眼也要写出来]

Reverse a singly linked list.

 

/**
 * 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 = null;

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

  

posted @ 2017-03-19 22:41  notesbuddy  阅读(112)  评论(0编辑  收藏  举报