Reverse Linked List

题目:

Reverse a linked list.

For linked list 1->2->3, the reversed linked list is 3->2->1

分析:

解法:

public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        // write your code here
        if (head == null) {
            return null;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        while (head.next != null) {
            ListNode newhead = head.next;
            head.next = newhead.next;
            newhead.next = dummy.next;
            dummy.next = newhead;
        }
        return dummy.next;
    }
}

results matching ""

    No results matching ""