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();
}
}
[Algorithm] Java链表反转
最新推荐文章于 2022-04-18 21:18:08 发布