Java实现单向链表反转
程序员文章站
2022-07-13 17:51:23
...
为了方便理解,我们以 1->2->3->4这个链表来做演示。输出的效果是4->3->2->1
package com.ctpia.qgw.v1.utils;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
Node node1=new Node(1);
Node node2=new Node(2);
Node node3=new Node(3);
Node node4=new Node(4);
node1.next=node2;
node2.next=node3;
node3.next=node4;
node4.next=null;
Node head=node1;
Node newHead=reverse(head);
System.out.println(newHead.value);
}
public static Node reverse(Node head){
if (head == null || head.next == null)
return head;
Node temp = head.next;
Node newHead = reverse(head.next);
temp.next = head;
head.next = null;
return newHead;
}
public static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
}
上一篇: js this