Reverse Linked List

来源:互联网 发布:浙江师范行知学院宿舍 编辑:程序博客网 时间:2024/05/20 14:24

Easy Reverse Linked ListMy Submissions

37%
Accepted

Reverse a linked list.

Example

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

Challenge Expand 

Reverse it in-place and in one-pass

Tags Expand 
Linked List


SOLUTION 1 directly distort the direction of the pointer.  BETTER

Oriented the pointer direction to let the current node point to its original previous node. ListNode prev is initialized to Null. At last, we return prev of head is Null.

public class Solution {    /**     * @param head: The head of linked list.     * @return: The new head of reversed linked list.     */    public ListNode reverse(ListNode head) {        if (head == null || head.next == null) {            return head;        }        ListNode prev = null;        while (head != null) {            ListNode temp = head.next;            head.next = prev;            prev = head;            head = temp;        }        return prev;    }

SOLUTION 2 Let tail.next to be the new Head. 

Add the last to the front. 

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 || head.next == null) {            return head;        }         ListNode tail = head;        while (tail.next != null) {            ListNode temp = tail.next.next;            tail.next.next = head;            head = tail.next;            tail.next = temp;        }        return head;    }}





0 0
原创粉丝点击