[Algorithm] Java链表反转

xiaoxiao2021-02-28  7

public class TurnBackLinkedList { public static void main(String[] args) { Node head = new Node(); Node cur = head; for(int i = 0; i < 10; i++) { int value = (int) (Math.random()*100); Node newNode = new Node(); newNode.value = value; cur.next = newNode; cur = cur.next; } printLinkedList(head); Node newHead = turnBackLinkedList(head); printLinkedList(newHead); } static Node turnBackLinkedList(Node head){ Node newHead = head; Node oldHead = head.next; newHead.next = null; while(oldHead != null) { Node temp = oldHead.next; oldHead.next = newHead; newHead = oldHead; oldHead = temp; } return newHead; } static class Node { Node next; int value; } static void printLinkedList(Node head) { Node cur = head; while(cur != null) { System.out.print(cur.value + " "); cur = cur.next; } System.out.println(); } }
转载请注明原文地址: https://www.6miu.com/read-2300119.html

最新回复(0)