UPI Study › Courses › Programming in C › Free lessons › Lesson 11.6 Free with a free account
Dynamic Linked List Operations
Programming in C · Chapter 11: Dynamic Memory, Linked Lists, Stacks, and QueuesSection 11.6 · lesson 76 of 786 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Workshop: A Stack and Queue System →← Implementing a QueueNext lesson: Workshop: A Stack and Queue System →
In this lesson
Inserting, deleting, and searching nodes anywhere in a linked list.
- Insert a node at any index by linking the new node before relinking prev
- Delete a node by key with prev and cur pointers, including the head case
- Search a list and return the first matching index or -1
- Test list functions on an empty list, the head, the tail, and a missing key
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (912 words). Read along, or search it.
Opening Question
A Line That Keeps Changing
The line at the Starlight Arcade is never fixed. A friend joins right behind someone. A name gets crossed off. In an array, every change means shuffling everyone along. A linked list just changes a few pointers. In this lesson, you'll insert a node anywhere, delete the one you want, and search by key. And you'll test the four cases that break careless code.
Insertion Plan
Two Pointer Changes in the Right Order
Each node holds a key, here a player number, and a next pointer. To insert 30 at index 2, walk to the node just before that spot. Call it prev. Here, that's 20. Then make two pointer changes, in this order. First, the new node points at what follows prev. Second, prev points at the new node. Do them the other way round, and the new node points at itself, and the rest of the list is cut off. At index zero there's no node before, so the new node becomes the head instead. That's why insert_at returns the head.
Code Walkthrough
Inserting at Any Position Safely
Here's plist dot h, a header holding the node and the basic tools. insert_at refuses a negative position. Then it makes the node. At position zero, the new node points at the old head, and it's returned as the new head. Otherwise, prev walks forward, pos minus one times, and stops early if it runs off the end. If prev is NULL, the position is past the end. The function says so, frees the unused node, and changes nothing. Otherwise come the two steps, in order: n arrow next gets prev arrow next, and then prev arrow next gets n.
Sample Run
Building 10, 20, 30, 40
In insert_demo, 30 goes into an empty list at index zero. Then 10 goes in front of it. 20 goes in at index 1, between 10 and 30. And 40 goes in at index 3, the end. Position 9 is too far for a four-node list. Build and run. First 10, 30. Then 10, 20, 30, 40. Then position 9 is past the end, and the list is unchanged.
Quick Check
Inserting at the Length Adds at the End
Quick check. The list holds 10, 20, 30 and 40, at indexes 0 to 3. Now insert_at is asked for index 4. Does that work, and if it does, where does 50 go? Pause and predict. Build and run: 50 is added at the end. Index 4 needs the node just before it, at index 3. That's 40. It exists, so prev isn't NULL. Only index 5 or more is past the end. Inserting at the length of the list is how you add at the end.
Deletion Plan
Bypass the Node, Then Free It
To remove a node, the node before it must point at the node after it. But a node can't look backward. So walk with two pointers. cur is the node being checked, and prev trails one step behind. When cur holds the key, bypass it: prev arrow next gets cur arrow next. Then free cur. Bypass first, free last. If the key is in the head, prev is still NULL. Then the head itself moves to the next node instead. Priya's first delete passed the middle case, but crashed on the head: it used prev arrow next while prev was still NULL.
Code Walkthrough
Walking With Prev and Cur
In pdelete dot h, prev starts at NULL, and cur at the head. The loop moves both, until cur holds the key, or runs off the end. found reports whether the key was there. If cur is NULL, nothing changes. If prev is NULL, it's the head, so head moves on. Otherwise, prev bypasses cur. Either way, cur is freed last.
Sample Run
Middle, Head, Tail, and Missing Key
delete_demo builds 10, 20, 30, 40, and then deletes four keys, one for each case: the middle, the head, the tail, and a missing key. Build and run. 20 goes from the middle, and 10 from the head. 40 goes from the tail. And 99 is not found, so the list stays at just 30.
Searching
Returning an Index or Minus One
search, in pfind dot h, walks the list once, counting positions as it goes. It returns the index of the first match. If there's no match, it returns minus one. That's the usual way to say not found, because no real index is negative.
Edge Cases
An Empty List Must Be Safe
edge_cases starts with an empty list. Printing it, deleting from it and searching it must all be safe. Build and run. The empty list prints as empty. Deleting 5 finds nothing, and search returns minus one. Then 100, 101 and 102 go in. Searching for 101 gives index 1, and 999 gives minus one. Finally, free_all frees all three nodes, and the caller sets head to NULL, so no stale pointer is left behind. free_all returns the count, which is a cheap check: compare it with the number of nodes you built.
Quick Check
Positions Shift After a Delete
Quick check. This list holds 7, 3, 9, 3. The key 3 appears twice. Then delete_key removes the key 3 once. What does search for 3 print now? Pause and predict. Build and run: two. delete_key removed the first 3, at index 1. The list is now 7, 9, 3. So the remaining 3 slid down to index 2. After a delete, old positions shift, so search again.
Key Takeaways
Insert, Delete, Search, and Test
To sum up. To insert, walk to the node before the spot. Point the new node at what follows, then point prev at it. To delete, walk with prev and cur. Bypass the node, then free it. At the head, move the head instead. search returns the first match's index, or minus one. And always test the four cases: an empty list, the head, the tail, and a missing key.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Dynamic Linked List Operations
How do you insert a node in the middle of a linked list in C?
How do you delete a node from a linked list in C?
How do you search a linked list for a value in C?
What edge cases should linked list functions be tested on?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →