270 likes | 287 Views
Linked List (2). Sanchai Yeewiyom School of Information & Communication Technology University of Phayao. Linked List Deletion. 3 methods Deleting a specified node from a linked list. Deletion of the first node in a linked list. Deletion of the last node in a linked list. 5. 8. 10.
E N D
Linked List (2) Sanchai Yeewiyom School of Information & Communication Technology University of Phayao
Linked List Deletion • 3 methods • Deleting a specified node from a linked list. • Deletion of the first node in a linked list. • Deletion of the last node in a linked list.
5 8 10 Deleting a specified node from a linked list. 1 head prev cur
Deleting a specified node from a linked list. • Algorithm prev -> next = cur -> next; delete cure; cur = null;
5 8 10 Deletion of the first node in a linked list. 1 head cur
Deletion of the first node in a linked list. • Algorithm cur = head; head = head -> next; delete cure; cur = null;
5 8 10 Deletion of the last node in a linked list. 1 head prev cur
Deletion of the last node in a linked list. • Algorithm prev -> next = cur -> next; delete cur; cur = null;
Conclude of Deletion • Deletion at the first node of a list. • Deletion at the last node or any node of a list.
Exp. Deletion void deletion(int val) { prev = null; cur = head; while (cur != null && val != cur->data) { prev = cur; cur = cur->next; } if cur = = null { cout << “not found” << endl; } else { if prev = = null { head = head->next; } else { prev->next = cur->next; cur->next = null; } delete cur; cur = null; } }
10 5 8 Circular Linked List
Circular Linked List • Principle • เริ่มต้นให้ list = null • สร้าง list ใหม่ • ให้ list ย้ายไปชี้ที่ตัวที่สร้างใหม่ (ตัวสุดท้าย)
Circular Linked List • Picture
Circular Linked List • Homework จงเขียน Function ของการ Delete Node ออกจาก Circular Linked List โดยกำหนดให้มีการรับค่าที่ต้องการลบเข้ามา จากนั้นทำการค้นหา เมื่อเจอ Node ที่ต้องการให้ทำการลบ Node นั้นออกไป
Doubly Linked List • A linked list that have 2 pointers (front, end)
Doubly Linked List data next precede
Doubly Linked List struct node; typedef node *ptrtype; struct node { int data; ptrtype precede, next; };
Insertion of Doubly Linked List • Picture
Insertion of Doubly Linked List • Algorithms newptr -> next = cur; newptr -> precede = cur -> precede; (cur -> precede) -> next = newptr; cur -> precede =newptr;
Deletion of Doubly Linked List • Picture
Deletion of Doubly Linked List • Algorithms (cur -> precede) -> next = cur -> next; (cur -> next) -> precede = cur -> precede;
Circular Doubly Linked List • เหมือนกับ CLL ทำงานเหมือนกัน • ต้องมี Dummy Head Node -999 listhead
Circular Doubly Linked List • สร้าง Dummy Head Node listhead = new node; listhead->data = -999; listhead->precede = listhead; listhead->next = listhead;
Insertion of Circular Doubly Linked List • Picture
Insertion of Circular Doubly Linked List • Algorithm
Deletion of Circular Doubly Linked List • Picture
Deletion of Circular Doubly Linked List • Algorithm