使用单链表实现反转
定义一个新的头节点
使用辅助节点将原先节点上遍历
将一个个节点插入到新头节点的后一个节点 即完成了反转
然后将原先头节点和新节点后的链表连接就可以了
package com.it.likedList;
/**
* @author Snail-Bo
* @date 2020/3/27 13:48
*/
class SingleLinkedListDemo3 {
public static void main(String[] args) {
//测试
UserNode3 user1 = new UserNode3(1, "小王", "1233");
UserNode3 user2 = new UserNode3(2, "赵六", "2222");
UserNode3 user3 = new UserNode3(3, "王五", "333");
SingleLinkedList3 sing = new SingleLinkedList3();
sing.add(user1);
sing.add(user2);
sing.add(user3);
System.out.println("遍历链表");
sing.list();
System.out.println("反转后:");
sing.reversetList();
sing.list();
}
}
class SingleLinkedList3{
//初始化一个头节点 ,一般是定义不变的,不放具体的数据
private UserNode3 head = new UserNode3(0,"","0");
public UserNode3 getHead() {
return head;
}
//添加用户节点
public void add(UserNode3 userNode) {
//头节点不能动,使用辅助的节点进行扫描,遍历
System.out.println(userNode);
UserNode3 temp = head;
//遍历链表,找到最后面的那个节点,来进行添加节点
while (temp.next != null) {
temp = temp.next; //temp进行后移
}
temp.next = userNode; //将要新添加的节点,添加到最后的节点上
}
/**
* 实现单链表的反转
*/
public void reversetList(){
if(head.next==null){
return; //判断链表为空
}
UserNode3 newHead = new UserNode3(0,"","0");//定义一个新的头节点
UserNode3 cur =head.next; //辅助节点,用于遍历
UserNode3 next=null; //用来记录辅助节点的下一个节点
while (cur!=null){
next =cur.next; //先记录原先链表的cur 的下一个节点
cur.next=newHead.next; //将该节点连接到新链表头节点的后面
newHead.next=cur; //将新的头节点和cur这个节点连接
cur=next; //将cur这个辅助节点 在原先的链表上向后移动。
}
head.next=newHead.next; //将原先的头节点和 新节点的后面的节点连接起来达到反转
}
//显示所有的链表(遍历)
public void list(){
//首先进行判断链表是否为空
if (head.next==null){
System.out.println("链表为空");
return;
}
UserNode3 temp = head.next;
//遍历head后面的节点 ,进行打印输出
while (temp!=null){
System.out.println(temp);
temp = temp.next; //将temp 进行后移
}
}
}
//定义用户的对象 即为每一个节点
class UserNode3{
private int id; //用户的编号
private String name; //用户的姓名
private String num; //用户的号码
UserNode3 next; // 指向下一个用户
//构造器
public UserNode3(int id, String name, String num) {
this.id = id;
this.name = name;
this.num = num;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public UserNode3 getNext() {
return next;
}
public void setNext(UserNode3 next) {
this.next = next;
}
@Override
public String toString() {
return "UserNode3{" +
"id=" + id +
", name='" + name + '\'' +
", num='" + num + '\'' +
", next=" + next +
'}';
}
}