带头节点的单向链表反转
程序员文章站
2022-03-01 19:50:21
...
package com.qcby.bilbil;
/**
* @author HuangHaiyang
* @date 2020/07/08
* @description: description
* @version: 1.0.0
*/
public class ReversalList {
private Node head=new Node(0,null);//带头节点
private Integer size=0;
public void add(Node node){
Node temp=head;
while (temp.next!=null){
if(temp.next.val.equals(node.val)){
throw new RuntimeException("已存在");
}
temp=temp.next;
}
temp.next=node;
size++;
}
public void show(){
Node temp=head.next;
while (temp!=null){
System.out.println(temp);
temp=temp.next;
}
}
public void Reverse(){
Node current=head.next;//辅助指针,遍历链表
Node next=head.next;//指向当前节点的下一个节点
Node resHead=new Node(0);//新的头
while (next!=null){
next=current.next;//暂时保存下一个节点
current.next=resHead.next;//将当前节点的next 指向 新的头的后面的内容
resHead.next=current;// 将当前节点插入到 新的头的后面 ,头插法
current=next;//向后遍历
}
head.next=resHead.next;
}
public static void main(String[] args) {
ReversalList reversalList=new ReversalList();
for (int i = 1; i <=10 ; i++) {
reversalList.add(new Node(i));
}
reversalList.show();
reversalList.Reverse();
System.out.println("===============================");
reversalList.show();
}
}
class Node{
public Integer val;
public Node next;
public Node() {
}
public Node(Integer val, Node next) {
this.val = val;
this.next = next;
}
public Node(Integer val) {
this.val = val;
}
@Override
public String toString() {
return "Node{" +
"val=" + val +
", next=" + next +
'}';
}
}
上一篇: Kotlin的inline内联函数
下一篇: 带头节点的双循环链表