class Node {
public int data;
public Node next; //存储对象引用
public Node(int data) {
this.data = data; //没有初始化next的引用,不知道next当前指向哪个节点
}
}
public class SingleList {
public Node head;//定位头节点的引用
public void addFirst(int data) {
Node node = new Node(data); //构造要插入的对象
if(this.head == null) {
this.head = node;
return;
} else {
node.next = this.head;
this.head = node;
}
}
public void show(){
Node cur=this.head; //从头开始
while(cur!=null){
System.out.print(cur.data+" ");
cur=cur.next;
}
System.out.println();
}
public Node reverse(){
Node pre=null;
Node cur=this.head;
Node newHead=null;
while(cur!=null){
Node curNext=cur.next;
if(curNext==null){
newHead=cur;
}
cur.next=pre;
pre=cur;
cur=curNext;
}
return newHead;
}
public void show1(Node newHead){ //重新打印
Node cur=newHead;
while(cur!=null){
System.out.print(cur.data+" ");
cur=cur.next;
}
System.out.println();
}
}
```java
public class TestDemo {
public static void main(String[] args) {
SingleList singleList=new SingleList();
singleList.addFirst(2);
singleList.addFirst(1);
singleList.addFirst(3);
singleList.addFirst(4);
singleList.addFirst(2);
singleList.show();
Node ret= singleList.reverse();
singleList.show1(ret);
}
}
反转单链表并打印
最新推荐文章于 2022-07-09 10:36:07 发布