UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » Remove all the nodes having certain value from the Linked List

#1 2010-02-11 05:53 AM

innqubus
Member
Registered: 2007-11-22
Posts: 29

Re: Remove all the nodes having certain value from the Linked List

Hello,
I need to write a function that deletes all the nodes having certain value in the Linked List.
My Linked List contains head and tail (which might be the same if there is only one element in the List). The deletion should take care of all conditions like if the value is present in head node, any middle node or the tail node. Its like deleting all nodes having the value as 5 in the list. 5->5->1->2->4->5.
Please help me with the function code in C.

typedef struct Node *pNode;

typedef struct{
pNode next;
int value;
}Node;

func_delAllnodeswithval(pNode **head, int val)
 {
 }


Thanks in advance.

Offline

#2 2010-02-11 06:26 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Remove all the nodes having certain value from the Linked List

If you turn it into a circular doubly linked list then deleting a node is always the
same.

You need to be able to do three things to write your function:

- Iterate through all nodes.

- Check a node's value.

- Remove a node from the list.

Just do those three things and you have your function.

The first two things are easy, so I guess you're uncertain how to remove
nodes for all cases? Removing the tail node is the same as removing middle
nodes. All you need to do extra for the first node is to update the head:

if (n == *head){
	*head = n->next;
}


So add this to the normal node removal code and it should just work.

Offline

  • Index
  • » C
  • » Remove all the nodes having certain value from the Linked List

Board footer

Powered by FluxBB