首页 > 其他 > 详细

反转链表

时间:2018-04-18 20:33:31      阅读:155      评论:0      收藏:0      [点我收藏+]

题目:输入一个链表,反转链表。

给定的结点结构:

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

 我的想法是:用三个结点first,head,second分别来表示前一个结点,当前结点,和后一个结点。三个结点的初始状态:first为null,head为第一个结点,second为第二个结点,三个结点同步移动,每移动一次,便将head的next由原来的指向second改为指向first,这样当second为null时,head刚好处于最后一个结点。

代码如下:

public ListNode ReverseList(ListNode head) {
        ListNode first, second;

        if (head == null) return null;

        first = null;
        second = head.next;
        head.next = first;

        while (second != null) {
            first = head;
            head = second;
            second = second.next;
            head.next = first;
        }

        return head;
    }

 

反转链表

原文:https://www.cnblogs.com/yi-hui/p/8877327.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!