public class HeroNode {
public int num;
public String name;
public String Nickname;
public HeroNode next;
public HeroNode(int num, String name, String nickname) {
this.num = num;
this.name = name;
Nickname = nickname;
}
@Override
public String toString() {
return "HeroNode{" +
"num=" + num +
", name='" + name + '\'' +
", Nickname='" + Nickname + '\'' +
'}';
}
}
import sun.reflect.generics.tree.VoidDescriptor;
import sun.rmi.transport.tcp.TCPEndpoint;
import javax.crypto.ExemptionMechanism;
import java.util.Stack;
public class SingleLinkedList {
private HeroNode head;
public static int count;
public SingleLinkedList() {
head = new HeroNode(0, "", "");
}
public HeroNode getHead() {
return head;
}
public void addByNumber(HeroNode someone)
{
HeroNode temp=head;
while (true)
{
if (temp.next==null)
{
temp.next=someone;
count++;
break;
}
if (temp.next.num>someone.num)
{
someone.next=temp.next;
temp.next=someone;
count++;
break;
}else if (temp.next.num==someone.num)
{
System.out.println("exist the same number,so the adding fails");
break;
}else{
temp=temp.next;
}
}
}
public void showing()
{
HeroNode temp=head;
while (temp.next!=null)
{
temp=temp.next;
System.out.println(temp);
}
}
public void update(HeroNode node)
{
HeroNode temp=head;
while (true)
{
if (temp.next==null) {
System.out.println("don't exit!");
break;
}
if (temp.next.num == node.num) {
temp.next.name=node.name;
temp.next.Nickname=node.Nickname;
break;
}
temp=temp.next;
}
}
public void delete(HeroNode node)
{
HeroNode temp=head;
while (true)
{
if (temp.next==null)
{
System.out.println("no such person!");
break;
}
if (temp.next.num==node.num)
{
temp.next=temp.next.next;
count--;
break;
}
temp=temp.next;
}
}
public void checkfromdown(int index) //通过倒序数来打印目标节点
{
HeroNode temp=head.next;
for (int i = 0; i <count-index ; i++) {
temp=temp.next;
}
System.out.println(temp);
}
public void reverseList(SingleLinkedList example) //存储结构上的反转,而不是打印实现的反转
{
if (example.head.next==null)
{
System.out.println("this list is null!");
return;
}
HeroNode reversehead=new HeroNode(0,"","");
HeroNode next=null;
HeroNode temp=example.head.next;
while (temp!=null) **//**需要注意这里的temp.next 和 temp 的区别,否则反转之后的列表缺少一个节点
{
next=temp.next;
temp.next=reversehead.next;
reversehead.next=temp;
temp=next;
}
example.head.next=reversehead.next;
showing();
}
public void Printreverse(HeroNode example) //未破坏原链表的存储顺序,而是借助栈的存储特性实现反向打印
{
if (example.next==null)
{
System.out.println("this is empty!");
return;
}
Stack<HeroNode> nodes = new Stack<>();
HeroNode temp=example.next;
while (temp!=null)
{
nodes.push(temp);
temp=temp.next;
}
while (nodes.size()>0)
{
System.out.println(nodes.pop());
}
}
}
单向列表-倒序打印,链表反转,打印倒数某节点
最新推荐文章于 2022-04-12 15:25:06 发布