TypechoJoeTheme

IT技术分享

统计

[LeetCode 206] Reverse Linked List [Java] [Runtime : 0MS]

2017-07-22
/
0 评论
/
610 阅读
/
正在检测是否收录...
07/22

1. Description

Reverse a singly linked list.

2. Runtime Distribution

3. Submission Details

4. Code

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

    ListNode pre = head;
    ListNode node = head.next;
    head.next = null;
    ListNode front = node.next;

    while (front != null) {
        node.next = pre;
        pre = node;
        node = front;
        front = front.next;
    }
    node.next = pre;
    return node;
}

6.Test

public class LeetCode0206 {

    static class ListNode {
        int val;
        ListNode next;
        public ListNode(int x) { val = x; }
    }

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

        ListNode pre = head;
        ListNode node = head.next;
        head.next = null;
        ListNode front = node.next;

        while (front != null) {
            node.next = pre;
            pre = node;
            node = front;
            front = front.next;
        }
        node.next = pre;
        return node;
    }

    public static void main(String[] args)
    {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        listNode1.next = listNode2;
        listNode2.next = null;
        LeetCode0206 leetcode = new LeetCode0206();
        ListNode head = leetcode.reverseList(listNode1);
        System.out.println(head.val + "->" + head.next.val);
    }
}
Linked
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/607/(转载时请注明本文出处及文章链接)