反转单链表
package LinkedList.test;
/**
* @version 1.0
* @auther WangCode
* @date 2021/4/3 16:08
*/
public class SingleLinkedListTest {
public static void main(String[] args) {
Node n1 = new Node(1, "123");
Node n2 = new Node(2, "23");
Node n3 = new Node(3, "3");
LinkedList linkedList = new LinkedList();
linkedList.add(n1);
linkedList.add(n2);
linkedList.add(n3);
linkedList.list();
linkedList.reverse(linkedList.getHead());
linkedList.list();
}
}
//定义一个节点
class Node{
public int no;
public String data;
public Node next;
//构造方法
public Node(int no, String data){
this.no = no;
this.data = data;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
", data='" + data + '\'' +
'}';
}
}
//创建单链表
class LinkedList{
//初始化头节点
private Node head = new Node(0,"");
public Node getHead() {
return head;
}
/**
* 添加节点
* @param node
*/
public void add(Node node){
Node temp = head;
while (true){
if (temp.next == null){//找到链表最后一个节点
break;
}
temp = temp.next;
}
temp.next = node;//在链表的最后添加新的节点
}
/**
* 遍历链表
*/
public void list(){
Node temp = head.next;
if (temp == null){
System.out.println("该链表为空");
return;
}
while(true){
if (temp == null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
/**
* 反转链表
* @param head 链表的头节点
*/
public void reverse(Node head){
if (head.next == null || head.next.next == null){
return;
}
//辅助指针,遍历原来的链表
Node temp = head.next;
//指向当前节点的下一个节点
Node next = null;
//初始化新链表的头节点
Node reverseHead = new Node(0,"");
//遍历原来的链表,每遍历一个节点,就将其取出,放在新的链表的最前端
while(temp != null){
next = temp.next;//保留当前节点的下一个节点
temp.next = reverseHead.next;//将temp的下一个节点指向新链表的最前端
reverseHead.next = temp;
temp = next;
}
//换回原来的头
head.next = reverseHead.next;
}
}
运行结果: