package com.zmz.algorithm.listnode;

/**
 * @author 张明泽
 * Create by 2022/5/28 15:40
 * 反转链表
 * LeetCode-206
 */
public class ReverseListNode2 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        ListNode result = reverse(head);
        traverse(result);
    }
    public static ListNode reverse(ListNode listNode) {
        ListNode pre = null;
        ListNode cur = listNode;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        // cur指向null了
        return pre;
    }
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static void traverse(ListNode listNode) {
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
}
最后修改:2022 年 05 月 29 日 10 : 20 PM
赏杯咖啡喝 谢谢您~