473,756 Members | 7,293 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Doubly Link List

How to swap two nodes of doubly Linklist

Nov 15 '05 #1
8 4169

sudhirlko2001 wrote:
How to swap two nodes of doubly Linklist


Dont expect us to do your homework. Please tell us what you tried and
if you are stuck at some point we would be glad to help you out.

OR better still try searching for a 'college.homewo rk' newsgroup.

Nov 15 '05 #2
Jaspreet wrote:
sudhirlko2001 wrote:
How to swap two nodes of doubly Linklist

Dont expect us to do your homework. Please tell us what you tried and
if you are stuck at some point we would be glad to help you out.

OR better still try searching for a 'college.homewo rk' newsgroup.


Yeah try the problem first, at least.
Nov 15 '05 #3
ya i tried it but i am unable to get proper algo for that .Sorry but
this not my assignment actually i asked this in a interview.

Thanks
Sudhir

Nov 15 '05 #4

sudhirlko2001 wrote:
ya i tried it but i am unable to get proper algo for that .Sorry but
this not my assignment actually i asked this in a interview.

Thanks
Sudhir


hopefully you did not get the job.

The algorithm is so trivial.
valueholder = nodeA.value
nodeA.value = nodeB.value
nodeB.value = valueholder

if the "value" portion of the node is too complex to handle this way
(maybe it is many fields), then you swap link pointers but the method
is the same. And totally independent of C programming.

Get a text book and study some fundamental algorithms.
Ed.

Nov 15 '05 #5
On Tue, 06 Sep 2005 10:51:42 -0700, Ed Prochak wrote:

sudhirlko2001 wrote:
ya i tried it but i am unable to get proper algo for that .Sorry but
this not my assignment actually i asked this in a interview.

Thanks
Sudhir
hopefully you did not get the job.

The algorithm is so trivial.
valueholder = nodeA.value
nodeA.value = nodeB.value
nodeB.value = valueholder


Which of course may fail if there are other pointers to nodeA or nodeB in
the system. Even if there aren't any now there might be in the future.
if the "value" portion of the node is too complex to handle this way
(maybe it is many fields), then you swap link pointers but the method is
the same. And totally independent of C programming.


That would be the usual method, the nice thing about a doubly linked list
is that all the pointers you have to change at easily accessible. Although
the method is easy it isn't trivial. There are a number of pointers to
update and you have to consider cases where forwards and backwards links
are null. It is easy to get wrong.

Lawrence
Nov 15 '05 #6

Lawrence Kirby wrote:
On Tue, 06 Sep 2005 10:51:42 -0700, Ed Prochak wrote:

sudhirlko2001 wrote:
ya i tried it but i am unable to get proper algo for that .Sorry but
this not my assignment actually i asked this in a interview.

Thanks
Sudhir
hopefully you did not get the job.

The algorithm is so trivial.
valueholder = nodeA.value
nodeA.value = nodeB.value
nodeB.value = valueholder


Which of course may fail if there are other pointers to nodeA or nodeB in
the system. Even if there aren't any now there might be in the future.


yes that does mess him up, but if he is at the level of job interviews,
he needs to think about such things himself. He should likely go back
to school. The fact he didn't even define the question clearly was one
reason why I even suggested that "solution".

if the "value" portion of the node is too complex to handle this way
(maybe it is many fields), then you swap link pointers but the method is
the same. And totally independent of C programming.


That would be the usual method, the nice thing about a doubly linked list
is that all the pointers you have to change at easily accessible. Although
the method is easy it isn't trivial. There are a number of pointers to
update and you have to consider cases where forwards and backwards links
are null. It is easy to get wrong.

Lawrence


But it is so simple it usually isn't even included in fundamental
algorithms texts. Other than the terminal node case, there is nothing
really different, and in fact it is easier since you likely have at
least one pointer to one of the nodes (iow, the temp holder). How can
he hope to get a programming job an not know this?

Bottom line is, this might be a comp.programmin g question, but it
really has nothing to do with C programming.

Have a great day Lawrence.

ed

Nov 15 '05 #7
Lawrence Kirby <lk****@netacti ve.co.uk>:
On Tue, 06 Sep 2005 10:51:42 -0700, Ed Prochak wrote:
The algorithm is so trivial.
valueholder = nodeA.value
nodeA.value = nodeB.value
nodeB.value = valueholder
Which of course may fail if there are other pointers to nodeA or
nodeB in the system. Even if there aren't any now there might be
in the future. if the "value" portion of the node is too complex to handle
this way (maybe it is many fields), then you swap link
pointers but the method is the same. And totally independent
of C programming.

That would be the usual method, the nice thing about a doubly
linked list is that all the pointers you have to change at
easily accessible. Although the method is easy it isn't trivial.
There are a number of pointers to update and you have to
consider cases where forwards and backwards links are null. It
is easy to get wrong.


I would try swapping node A and node B this way:

In order to leave the structure of the list unchanged, I suggest
to not simply remove the nodes A and B from the list and reinsert
them afterwards but to use a temporary node Temp:

1) replace node A with node Temp
2) replace node B with node A
3) replace node Temp with node B

Note: If A and B are elements not of the same but of distinct
lists listA and listB respectively, then afterwards A will be in
listB where B was and vice versa.

Replacing a node C with a node D can be done by

1) inserting node D after node C
2) removing node C from the list.

This approach has the advantage that it works even if node C is
the only element of the list, regardless, whether the list is a
ring list or has a head and a tail.

C code (untested):

#include <stdlib.h> /* NULL, EXIT_SUCCESS */
#include <stdio.h> /* printf() */

struct link
{
struct link * prev, * next;
};

void insertAfter(str uct link * where, struct link * what)
/* Note: *what need not be initialized but may not be part of
* any list, because that list would be corrupted.
*/
{
struct link * succ = where->next;
/* Note: If *where is the last link in the list, then
* where->next == NULL.
*/

/* Update next and prev pointers in *what:
* After the insertion *succ will be the successor of *what.
* After the insertion *where will be the predecessor of
* *what:
*/
what->next = succ;
what->prev = where;

/* Update both the next pointer in *where and the prev pointer
* in *succ to point to *what:
*/
where->next = what;
if (succ != NULL)
succ->prev = what;
}

void removeLink(stru ct link * what)
{
struct link * pred = what->prev; /* may be NULL or even what */
struct link * succ = what->next; /* may be NULL or even what */

if (pred != NULL) pred->next = succ;
if (succ != NULL) succ->prev = pred;

/* prevent next and prev ptr.s in *what from dangling around:
*/
what->next = NULL;
what->prev = NULL;
}

void replaceWith(str uct link * what, struct link * substitute)
/* Note: *substitute need not be initialized but may not be
* part of any list, because that list would be corrupted.
*/
{
insertAfter(wha t, substitute);
removeLink(what );
}

void swap(struct link * a, struct link * b)
{
struct link temp;
/* .next and .prev need not be initialized, because
* replaceWith() does that already.
*/

replaceWith(a, &temp);
replaceWith(b, a);
replaceWith(&te mp, b);
}

/* Example: Create a list of three strings and exchange the first
* and the third elements.
*/

struct stringListElem
{
struct link link; /* must be first component of this struct */
const char *data;
};

struct stringListElem * elemFromLink(co nst struct link * l)
{
/* This ptr type cast is legal if and only if l points to the
* .link of a struct stringListElem object and .link is the first
* component of struct stringListElem.
*/
return (struct stringListElem *)l;
}

int main(void)
{
struct stringListElem a, b, c;

a.data = "a";
b.data = "b";
c.data = "c";

{
struct link tempHandle = { NULL, NULL };
/* Initialize tempHandle to { &tempHandle, &tempHandle } if
* you want a ring list.
*/

/* Initialize a.link by inserting a.link in tempHandle's list
* and therewith expelling tempHandle from its own list. Thus,
* tempHandle may cease to exist afterwards.
*/
replaceWith(&te mpHandle, &a.link);
}
insertAfter(&a. link, &b.link);
insertAfter(&b. link, &c.link);

printf("List is\n");
{
unsigned i; struct link *l;
for (i = 1, l = &a.link; i <= 3; i++, l = l.next)
printf("%u: %s\n", i, elemFromLink(l)->data);
}

printf("exchang ing...\n");
swap(&a.link, &c.link);

printf("List is\n");
{
unsigned i; struct link *l;
for (i = 1, l = &c.link; i <= 3; i++, l = l.next)
printf("%u: %s\n", i, elemFromLink(l)->data);
}

/* remove the three elements from the list before their
* lifetime ends.
*/
removeLink(&a.l ink);
removeLink(&b.l ink);
removeLink(&c.l ink);

return EXIT_SUCCESS;
}
Nov 15 '05 #8
Thanks Friedhelm

Nov 15 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2217
by: D. Beckham | last post by:
I wrote the following code to create a short doubly-link list of three strings: "one", "two", and "three". I would like to know if I set them up correctly, so that they point to one another. DLLNode class has already been created. Basically, "one" is the head node, "two" is the mid node, and "three" is the tail or the last node. I would like to know if my algorithm for setting up doubly-linked node are correct before I proceed to...
5
3230
by: free2cric | last post by:
Hi, how to detect head and tail in cyclic doubly link list ? Thanks, Cric
8
680
by: Jack | last post by:
Hi I have a somewhat easy question. Lets say I have a link list (struct) with three items in it and I want to delete the middle item. Once I point the pointer from the first item to the third and delete the second item's pointer, do I need to delete anything else as in do I need to delete the actual data in the middle of 2 and 3. I am thinking this because once I reassign the pointer from 1 to 3 there is no way i can access 2 again.
4
1945
by: srad | last post by:
Hi..Im writting a doubly link list in c++,compiled with Turbo c++, but my Add_at_first method seems not working,i couldnt find any problem in the code... here is the code : #include <iostream.h> class node { friend class linklist; public : int num; node *next; node *prev; };
3
2669
by: maruf.syfullah | last post by:
Consider the following Class definitions: class AClass { int ai1; int ai2; public: CClass* c; AClass(){}
4
2050
by: ravi | last post by:
Can any body help in finding the middle element of a link list in an effective manner i know the simple solution of using two pointers and increment one pointer by one and second by two. but i want a effective algo both in terms of memory and time
3
1731
by: ravi | last post by:
Can any body tell me an effective algo to sort a doubly link list algo must be time as well as memory effective
9
1784
by: ratika | last post by:
can anyone tell me how to delete a certain node in a doubly circular link list
2
2137
by: caritor | last post by:
hi.... just send me the coding in c program for doubly link list..... regards... S.Pradeepkumar
0
9894
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9679
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9676
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9541
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8542
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7078
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5156
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3141
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2508
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.