Reverse Linked List(leetcode206)

Reverse a singly linked list.node

Example:git

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:github

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

public static ListNode reverseList(ListNode head) {

    ListNode headNew = null;
    ListNode node = head;
    while(null != node){

        ListNode node2 = new ListNode(node.val);
        node2.next = headNew;
        headNew = node2;
        node = node.next;
    }
    return headNew;

}

測試一下:ui

int array[] ={1,2,3,4,5};
    ListNode head = ListNode.buildeListNode(array);
    ListNode headNew =  reverseList(head);
    ListNode.printListNode(headNew);
}

輸出:code

git:https://github.com/woshiyexinjie/leetcode-xinblog

相關文章
相關標籤/搜索