首页 > 编程语言 > 详细

【算法基础】LeetCodeReverseListNode_反转链表

时间:2020-06-29 00:36:12      阅读:99      评论:0      收藏:0      [点我收藏+]
###反转链表

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

public class LeetCodeReverseListNode {

    public static void main(String[] args) {
        ListNode head = new ListNode(0);
        ListNode node1 = new ListNode(100);
        ListNode node2 = new ListNode(120);
        head.next = node1;
        node1.next = node2;
        node2.next = null;
        reverseList(head);
    }

    public static ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode tem = null;
        while (cur != null){
            //记录下一个节点
            tem = cur.next;
            //把当前节点的指针指向到前一个节点
            cur.next = pre;
            //前进一步
            pre = cur;
            //前进一步
            cur = tem;
        }
        return head;
    }
}

参考:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/solution/ru-guo-ni-kan-wan-ping-lun-he-ti-jie-huan-you-wen-/

【算法基础】LeetCodeReverseListNode_反转链表

原文:https://www.cnblogs.com/wtb123456/p/13205597.html

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