龙空技术网

链表反转

和乐赢 14

前言:

当前朋友们对“链表反转java代码”可能比较关注,我们都需要了解一些“链表反转java代码”的相关文章。那么小编同时在网上收集了一些对于“链表反转java代码””的相关资讯,希望各位老铁们能喜欢,大家一起来学习一下吧!

/** * 链表反转 */public class ListNode {    public Integer num;    public ListNode next;    public ListNode(Integer num) {        this.num = num;    }    public static void main(String[] args) {        ListNode node = new ListNode(1);        ListNode node2 = new ListNode(2);        ListNode node3 = new ListNode(3);        ListNode node4 = new ListNode(4);        node.next = node2;        node2.next = node3;        node3.next = node4;        ListNode tempPrint = node;        while (tempPrint != null) {            System.out.println(tempPrint.num);            tempPrint = tempPrint.next;        }        System.out.println("----------反转-------");        ListNode reverNode = reverseNode(node);        while (reverNode != null) {            System.out.println(reverNode.num);            reverNode = reverNode.next;        }    }    public static ListNode reverseNode(ListNode node) {        ListNode pre = null;        ListNode curr = node;        if (curr == null) {            return null;        }        if (curr.next == null) {            return node;        }        while (curr != null) {            ListNode temp = curr.next;            curr.next = pre;            pre = curr;            curr = temp;        }        return pre;    }}

标签: #链表反转java代码