Dynamic Linked List Operations, Explained with Code Examples

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

← Implementing a QueueNext lesson: Workshop: A Stack and Queue System →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
Walk to the node just before the target position, called prev, then make two pointer changes in this order: n->next = prev->next, then prev->next = n. Reversing the order makes the new node point at itself and cuts off the rest of the list. Index 0 has no prev, so there the new node points at the old head and becomes the new head.
How do you delete a node from a linked list in C?
Walk with two pointers, cur checking each node and prev trailing one step behind. When cur holds the key, bypass it with prev->next = cur->next, then free cur. If the match is the head, prev is still NULL, so move head to cur->next instead. Using prev->next while prev is NULL crashes, which is why the head case needs its own branch.
How do you search a linked list for a value in C?
Walk the list once from the head, counting positions, and return the index of the first node whose key matches. If the walk reaches NULL without a match, return -1, a common way to signal not found because no real index is negative. Positions shift after a delete: in 7, 3, 9, 3, removing the first 3 moves the other one to index 2.
What edge cases should linked list functions be tested on?
Test four cases: an empty list, the head node, the tail node, and a key or position that is not there. Printing, deleting from, and searching an empty list should all be safe. Deleting the head must move the head pointer, and inserting at an index equal to the list's length should add at the end, while a larger index should change nothing.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Programming in C
3 credits · NCCRS
Enroll →