【算法基础】LeetCodeReverseListNode_反转链表

2021-05-01 22:27

阅读:620

标签:code   void   class   ping   href   指针   next   ring   com   

###反转链表

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_反转链表

标签:code   void   class   ping   href   指针   next   ring   com   

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


评论


亲,登录后才可以留言!