单链表
添加操作:
public void add(HeroNode heronode) {
HeroNode temp = firstnode;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = heronode;
}
遍历:
public void list() {
if (firstnode.next == null) {
System.out.println("链表为空");
return;
}
HeroNode temp = firstnode.next;
while (true) {
if (temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
对添加的优化(根据no添加到指定位置):
public void addByOrder(HeroNode heronode) {
HeroNode temp = firstnode;
boolean flag = false;
while (true) {
if (temp.next == null) {
break;
}
if (temp.next.number > heronode.number) {
break;
} else if (temp.next.number == heronode.number) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
System.out.println("准备插入的编号:" + heronode.number + "\n" + "已存在");
} else {
heronode.next = temp.next;
temp.next = heronode;
}
}
单链表结点的修改:
public void update(HeroNode newheronode) {
if (firstnode.next == null) {
System.out.println("链表为空");
}
HeroNode temp = firstnode.next;
boolean flag = false;
while (true) {
if (temp == null) {
break;
}
if (temp.number == newheronode.number) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
temp.name = newheronode.name;
temp.nickname = newheronode.nickname;
} else {
System.out.println("没有找到编号为 " + newheronode.number + "的结点" + "\t" + "不能修改");
}
}
删除: 注意:因为此时是单链表,必须找到待删除结点的前一个结点,否则删除不了。
public void dellist(HeroNode heronode) {
HeroNode temp = firstnode;
boolean flag = false;
while (true) {
if (temp.next == null) {
break;
}
if (temp.next.number == heronode.number) {
flag = true;
break;
}
temp = temp.next;
}
if (flag) {
temp.next = temp.next.next;
} else {
System.out.println("要删除的结点:" + heronode.number + "\t" + "不存在");
}
}
public static int count(HeroNode head) {
HeroNode temp = head.next;
int count = 0;
while (true) {
if (temp == null) {
break;
}
temp = temp.next;
count++;
}
return count;
}
- 查找单链表中倒数第k个结点
核心:通过[ 链表的大小(有效结点)-k = 移动的次数 ] 定位到查找的结点。
public static HeroNode getLastNode(HeroNode head, int index) {
HeroNode temp = head.next;
int size = getLength(head);
if (head.next == null) {
return null;
}
if (index <= 0 || index > size) {
return null;
}
for (int i = 0; i < size - index; i++) {
temp = temp.next;
}
return temp;
}
- 单链表的反转
头插法: 核心:将新链表的next域赋值给要插入结点的next域 —> node.next = reverse.next 将要插入的结点赋值给新链表的next域 —>reverse.next = node
public static void reverseList(HeroNode head) {
if (head.next == null || head.next.next == null) {
return;
}
HeroNode newNode = new HeroNode(0, "", "");
HeroNode temp = null;
HeroNode cur = head.next;
while (cur != null) {
temp = cur.next;
cur.next = newNode.next;
newNode.next = cur;
cur = temp;
}
head.next = newNode.next;
}
|