import java.util.Stack;
public class LinkedListReverse {
public static void main(String[] args) {
SingleLinkedList3 singleLinkedList = new SingleLinkedList3();
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
singleLinkedList.addNode(node1);
singleLinkedList.addNode(node2);
singleLinkedList.addNode(node3);
singleLinkedList.addNode(node4);
singleLinkedList.show(singleLinkedList.head);
// //反序遍历链表
// System.out.println("反序遍历链表~");
// reverseList(singleLinkedList.head);
// System.out.println("反序遍历不会改变链表结构");
// singleLinkedList.show(singleLinkedList.head);
System.out.println("进行链表的反转~~~~~~~");
singleLinkedList.reverseLinkedList();
singleLinkedList.show(singleLinkedList.head);
System.out.println("The size of the SingleLinkedList is:" + singleLinkedList.size());
}
public static void reverseList(Node head) {
if (head.next == null || head.next.next == null) {
return;
}
//创建一个栈,将各个节点压入栈
Stack<Node> stack = new Stack<>();
Node cur = head.next;
//将链表所有的节点压入栈
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
while (stack.size() > 0) {
System.out.println(stack.pop());
}
}
}
class SingleLinkedList3 {
public Node head;
public SingleLinkedList3() {
head = new Node(-1);
}
public void addNode(Node newNode) {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
public int size() {
if (head.next == null) {
System.out.println("链表为空~");
return 0;
}
Node temp = head;
int count = 0;
while (temp.next != null) {
count++;
temp = temp.next;
}
return count;
}
public void show(Node node) {
Node temp = node;
while (temp.next != null) {
System.out.println(temp.next);
temp = temp.next;
}
}
public void reverseLinkedList() {
if (head.next == null || head.next.next == null) {
throw new RuntimeException("链表为空或者只有一个结点,无需反转");
}
Node reverseNode = new Node(-1);
//定义一个辅助的变量,帮助我们遍历原来的链表
Node cur = head.next;
//指向当前结点[cur]的下一个结点
Node next = null;
//遍历原来的链表,每遍历一个结点,就将其取出,并放在新的链表的最前端
while (cur != null) {
next = cur.next; //先保存当前节点的下一个节点,因为后面需要使用
cur.next = reverseNode.next; //将cur的下一个节点指向新的链表的最前端【cur即为添加进新链表最前端的元素】
reverseNode.next = cur;
cur = next; //进入下一个节点
}
//将head.next指向reverseHead.next,实现单链表的反转
head.next = reverseNode.next;
}
}
单链表的反转
最新推荐文章于 2023-08-08 15:19:15 发布