



































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Problem: Reverse Linked List. Leetcode questions #206. // One possible solution. Node* reverseList(struct ListNode* head).
Typology: Schemes and Mind Maps
1 / 43
This page cannot be seen from the preview
Don't miss anything!




































Credit: Carey Nachenberg, Junheng Hao
https://tinyurl.com/StudentsToLAsW
○ Key component as unit: Node (with value and pointer to next node) ○ Head pointer → points to the first term
○ Insertion ○ Search ○ Removal
○ Efficient insertion, flexible memory allocation, simple implementation ○ High complexity of search
Basis
typedef int ItemType; Struct Node { ItemType value; Node *next; };
a) Create a new node and call the pointer p b) Make its next pointer point to the first item c) Make the head pointer to the new node
Insertion: Add a new node to a list
//Skeleton: Linked list insertion //=====================================
//insert as head p->next = head; Head = p;
//insert after end: End node: q q->next = p; p->next = nullptr;
//insert in the middle: node q p->next = q->next; q->next = p;
head
new
p
p head
p
head
Removal
q->next = p->next; delete p ● What if p == head? What if p prints to the last node in the linked list?
// Skeleton Code: Linked list removal // =====================================
void remove(int valToRemove, Node* head) { Node *p = head, *q = NULL; while (p != NULL) { if (p->value == valToRemove) break; q = p; p = p->next;} if (p == NULL) return; if ( p == head ) //special case head = p->next; else q->next = p->next; delete p; }
q p
Conclusion
Insertion: How many cases to consider?
Insertion: Before head / After tail
○ Set the prev of head to the new node p ○ Set the next of p to head ○ p becomes the new head ○ head->prev = NULL;
○ Similar to insertion before head (try it yourself!)
Insertion to empty list / Search
head = tail = p; p->next = p->prev = NULL;
Removal
Copy a doubly linked list (and more)
○ There is no NULL at the end. ○ Can be a singly circular linked list or doubly circular linked list.
○ Any points can be head (starting point). ○ Implementation for queue. ○ Fit to repeatedly go around the list.
Motivation and properties
We can maintain a pointer to the last inserted node and front can always be obtained as next of last.
Leetcode questions #
○ Tell whether the linked list is circular ○ Tell whether there is a loop in the linked list (this is much harder!)