reverse linkedlist

This commit is contained in:
lixiangrong 2021-04-04 22:32:26 +08:00
parent 69d714f19a
commit 2953e48009

View File

@ -51,6 +51,11 @@ public class SingleLinkedListDemo {
singleLinkedList.list(); singleLinkedList.list();
// 反转链表
reverseList(singleLinkedList.getHead());
System.out.println("反转之后的链表");
singleLinkedList.list();
HeroNode newHeroNode = new HeroNode(3, "小吴", "智多星.."); HeroNode newHeroNode = new HeroNode(3, "小吴", "智多星..");
singleLinkedList.update(newHeroNode); singleLinkedList.update(newHeroNode);
System.out.println("修改后的链表"); System.out.println("修改后的链表");
@ -60,11 +65,34 @@ public class SingleLinkedListDemo {
System.out.println("删除 no 为 3 的节点"); System.out.println("删除 no 为 3 的节点");
singleLinkedList.list(); singleLinkedList.list();
} }
/**
* 反转链表
*/
public static void reverseList(HeroNode head) {
HeroNode pre = null;
HeroNode cur = head.next;
while (cur != null) {
HeroNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
head.next = pre;
}
} }
class SingleLinkedList { class SingleLinkedList {
private final HeroNode head = new HeroNode(0, "", ""); private final HeroNode head = new HeroNode(0, "", "");
public HeroNode getHead() {
return head;
}
public void list() { public void list() {
HeroNode temp = head.next; HeroNode temp = head.next;
while (temp != null) { while (temp != null) {
@ -131,7 +159,7 @@ class SingleLinkedList {
while (true) { while (true) {
if (temp.next == null) { if (temp.next == null) {
System.out.printf("没找到要删除 %d 节点\n", no); System.out.printf("没找到要删除 %d 节点\n", no);
break; break;
} }