function swapNode does not work in doubly linked list - c

Function swapNode swaps 2 nodes in list. The function create node* temp to store temporary data then swaps the data of node* A and node* B. I can not understand why it does not work. Below here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
struct node;
struct list;
typedef struct node node;
typedef struct list list;
struct node
{
int point;
char name[30];
node *next;
node *prev;
};
struct list
{
node *head;
node *tail;
int count;
};
node *allocateNewNode(int point, char name[30], node *prev, node *next);
list *createList();
bool insertHead(list *listNode, int point, char name[30]);
bool compareName(char a[30], char b[30]);
bool swapNode(list *listNode, char nameA[30], char nameB[30]);
int main()
{
list *listNode = createList();
insertHead(listNode, 10, "abc def");
insertHead(listNode, 9, "qwe rty");
insertHead(listNode, 8, "ui op");
insertHead(listNode, 30, "fgh jkl");
insertHead(listNode, 1234, "akaka");
swapNode(listNode, "ui op", "abc def");
node *temp = listNode->head;
while (temp != NULL)
{
printf("%-20s%d\n", temp->name, temp->point);
temp = temp->next;
}
free(temp);
printf("\n%d", listNode->count);
return 0;
}
node *allocateNewNode(int point, char name[30], node *prev, node *next)
{
node *newNode = (node *)malloc(sizeof(node));
newNode->point = point;
strcpy(newNode->name, name);
newNode->next = next;
newNode->prev = prev;
return newNode;
}
list *createList()
{
list *listNode = (list *)malloc(sizeof(list));
listNode->count = 0;
listNode->head = NULL;
listNode->tail = NULL;
return listNode;
}
bool insertHead(list *listNode, int point, char name[30])
{
node *newNode = allocateNewNode(point, name, NULL, listNode->head);
if (listNode->head)
listNode->head->prev = newNode;
listNode->head = newNode;
if (listNode->tail == NULL)
listNode->tail = newNode;
++listNode->count;
return true;
}
bool compareName(char a[30], char b[30])
{
for (int i = 0; i < 31; i++)
{
if (a[i] != b[i])
return false;
if (a[i] == '\0')
break;
}
return true;
}
bool swapNode(list *listNode, char nameA[30], char nameB[30])
{
node *A = NULL, *B = NULL;
node *temp = listNode->head;
for (int i = 0; i < listNode->count - 1; i++)
{
if (compareName(temp->name, nameA))
A = temp;
else if (compareName(temp->name, nameB))
B = temp;
temp = temp->next;
if (A || B)
break;
}
if (!A || !B)
return false;
else if (A == B)
return false;
*temp = *A;
*A = *B;
*B = *temp;
if (A->prev)
A->prev->next = A;
if (A->next)
A->next->prev = A;
if (A->prev)
A->prev->next = A;
if (A->next)
A->next->prev = A;
free(temp);
return true;
}
tks for your help

In swapNode, A and B are initially NULL. The loop that searches for the two matching nodes terminates early when either node is found:
if (A || B)
break;
At most one of A and B will be non-NULL when the loop terminates so at least one of A and B will be NULL. This causes the function to return false:
if (!A || !B)
return false;
To avoid that, you should change the loop to break when both A and B are non-NULL:
if (A && B)
break;
Also, the loop is only checking count - 1 elements of the list, so it ignores the final element:
for (int i = 0; i < listNode->count - 1; i++)
To check all elements, you need to change that to:
for (int i = 0; i < listNode->count; i++)
Alternatively, you could ignore listNode->count and check the temp pointer instead:
while (temp != NULL)
That will work because temp is initialized to listNode->head, which will be NULL for an empty list, and for a non-empty list, the next member of the final element on the list is NULL, so temp = temp->next; will set temp to NULL when the final element has been checked.
There are other problems in swapNode related to the actual swapping of the nodes after they have been found. The original code to do that looks totally wrong:
*temp = *A;
*A = *B;
*B = *temp;
The temp pointer will either be NULL or will point to a node after the A and B nodes.
if (A->prev)
A->prev->next = A;
if (A->next)
A->next->prev = A;
if (A->prev)
A->prev->next = A;
if (A->next)
A->next->prev = A;
The code does not alter listNode->head or listNode->tail when A or B is at the head or tail of the list.
free(temp);
Why is it freeing temp here when all the function is supposed to be doing is swapping nodes?
The code to swap the nodes A and B needs to be able to deal with neither, either or both nodes being at the end(s) of the list, and with A and B being adjacent nodes in either order. Here is a sequence to handle all that:
/* update list head pointer */
if (listNode->head == A)
listNode->head = B;
else if (listNode->head == B)
listNode->head = A;
/* update list tail pointer */
if (listNode->tail == A)
listNode->tail = B;
else if (listNode->tail == B)
listNode->tail = A;
/* update ->prev->next pointers */
if (A->prev != NULL && A->prev != B)
A->prev->next = B;
if (B->prev != NULL && B->prev != A)
B->prev->next = A;
/* update ->next->prev pointers */
if (A->next != NULL && A->next != B)
A->next->prev = B;
if (B->next != NULL && B->next != A)
B->next->prev = A;
/* update A->prev and B->prev pointers */
if (A->prev == B)
{
A->prev = B->prev;
B->prev = A;
}
else if (B->prev == A)
{
B->prev = A->prev;
A->prev = B;
}
else
{
temp = A->prev;
A->prev = B->prev;
B->prev = temp;
}
/* update A->next and B->next pointers */
if (A->next == B)
{
A->next = B->next;
B->next = A;
}
else if (B->next == A)
{
B->next = A->next;
A->next = B;
}
else
{
temp = A->next;
A->next = B->next;
B->next = temp;
}

Using a debugger you would see that function swapNode returns at
if (!A || !B)
return false;
If you would step through the for loop you could see that you break from the loop when at least one of A and B is set, i.e. when the first matching node is found.
if (A || B)
break;
Change this to
if (A && B)
break;

Related

Linked list insert function returns wrong while tested with unity

i'm working on a simple doubly linked list implementation in c, i've created my structures as follows.
typdef struct node{
void *data;
struct node *next, *prev;
}node;
typedef struct list{
struct node *head, *tail;
size_t size;
}list;
I'm inserting elements in my linked list using this function and everything seems to work fine. Let's
assume i'm filling my list with integers calling the function 4 times to insert {2,4,6,8}.
When i execute my print function it correctly returns 2,4,6,8.
void insert_node(list *l, void *elem)
{
node *n = create_node(elem); //here i just create and initialize the new node;
if(l->size == 0){
l->head = n;
l->tail = n;
}else{
l->tail->next = n;
n->prev = l->tail;
l->tail = n;
}
l->size++;
}
The problem rises when i try to test my function with unity, i wrote this simple unit test:
void test_list_insert(){
list *l = list_test(); //this function creates a list and inserts in it {2,4,6,8} as values
TEST_ASSERT_EQUAL_INT(2, *(int*)(get_node_i(l,0))->data);
TEST_ASSERT_EQUAL_INT(4, *(int*)(get_node_i(l,1))->data); //problem seems to be here..
TEST_ASSERT_EQUAL_INT(6, *(int*)(get_node_i(l,2))->data);
TEST_ASSERT_EQUAL_INT(8, *(int*)(get_node_i(l,3))->data);
}
When i execute my unit test i get this output:
test.c:73:test_list_insert:FAIL Expected 4 was 1
At this point the problem seems related to the 'get_node_i' function
which is used to retrieve the element in the i-th position of the list... here's the function:
node *get_node_i(list *l, int pos){
if(pos > l->size || pos < 0){
return NULL;
}
node *curr = l->head;
int currPos = 0;
if(pos == 0) return curr;
while(curr != NULL){
if(currPos == pos){
return curr;
}
currPos++;
curr = curr->next;
}
return NULL;
}
I've tried to execute my print function inside the unit test and i discovered that it prints correctly just the first two nodes (2,4) and for the other nodes it prints pointers... That for me is quite strange as if i try to execute the print function in any other part of my code it returns the list correctly..
Here's how i create lists and nodes
//create new node
node* create_node(void * elem){
node *n = (node *)malloc(sizeof (node));
n->data = elem;
n->next = NULL;
n->prev = NULL;
return n;
}
//create an empty list
list *create_list(){
list *l = (list *)malloc(sizeof(list));
l->size = 0;
l->head = NULL;
l->tail = NULL;
return l;
}
Here's the list_test function and the print function,
list* list_test(){
list *l = create_list();
int a = 2;
int b = 4;
int c = 6;
int d = 8;
insert_node(l, &a);
insert_node(l, &b);
insert_node(l, &c);
insert_node(l, &d);
return l;
}
//print the list
void print_list(list *l){
node *tmp = l->head;
while(tmp != NULL){
printf("%d\t" , *(int *)tmp->data);
tmp = tmp->next;
}
}
if something else needs to be clarified, let me know, thanks.
In your function list_test you insert the address of local variables. So node->data is assigned the address of a local variable. When the function returns, the data pointed by these address will change.
The function list_test should be something like the following:
list* list_test(){
list *l = create_list();
int a = 2, *ap = malloc(sizeof(int));
int b = 4, *bp = malloc(sizeof(int));
int c = 6, *cp = malloc(sizeof(int));
int d = 8, *dp = malloc(sizeof(int));
*ap = a;
*bp = b;
*cp = c;
*dp = d;
insert_node(l, ap);
insert_node(l, bp);
insert_node(l, cp);
insert_node(l, dp);
return l;
}

Double linked lists: swapping function doesn't always work

I have written this code and in general works good, but trying to run these particular lines in main, when we arrive to the point in which i == 74 the elements of the list are 4 - 11 - 18 - 4 - 10 - 18 - 17 - 22 - 14 - 29 and the swapNodes() function has to swap the two nodes with the keys 18, but instead I get these elements: 4 - 18 - 4 - 10 - 18 - 17 - 22 - 14 - 29. I tried to initialize the list with the exact values as before "swapping" and then try to swap these two nodes and everything works as it should.
PS: I would appreciate if someone could help me to write the swapNodes() function with fewer lines but that's not a necessity at this moment.
typedef struct _node{
int key;
struct _node *next;
struct _node *prev;
}node;
node* createNode(int key){
node* a = (node*)malloc(sizeof(struct _node));
a->key = key;
a->next = NULL;
a->prev = NULL;
return a;
}
void printList(node* head){
while (head != NULL){
printf("%d", head->key);
if(head->next != NULL) printf(" - ");
head = head->next;
}
printf("\n");
}
void fillList(node** head, int dim){
int i;
for(i=0; i<dim; i++)
listInsert(head, createNode(rand()%30));
}
//findes a node given an index, the indices start from 1
node** findNode(node** head, int index){
int i;
for(i=1; i<index; i++)
head = &(*head)->next;
if(head != NULL) return head;
else return NULL;
}
void listInsert(node** head, node* node){
if((*head) == NULL){
(*head) = node;
return;
}
node->next = (*head);
(*head)->prev = node;
(*head) = node;
}
int main(){
node* list = NULL;
fillList(&list, 10);
int i, a, b;
for(i=0; i<100; i++){
printList(list);
a = rand()%10 +1;
b = rand()%10 +1;
swapNodes(&list, *findNode(&list, a), *findNode(&list, b));
printList(list);
printf("\n");
}
return 0;
}
EDIT:
I managed to rewrite the swapNodes() function but this time executing the same lines in main I get a loop in the list for i==15, a==4 and b==2. Again if I try to manualy swap any of the nodes the function works fine.
void swapNodes(node** head, node* a, node* b){
node* aPrev = a->prev;
node* aNext = a->next;
node* bPrev = b->prev;
node* bNext = b->next;
if(a == b) return;
if(a->prev == b ||
(b->prev == NULL && a->next == NULL) ||
(b->prev == NULL && b->next == a) ||
a->next == NULL) return swapNodes(head, b, a);
if(a->prev == NULL)
(*head) = b;
else if(b->prev == NULL)
(*head) = a;
if(a->next == b){
if(aPrev != NULL) aPrev->next = b;
b->prev = aPrev;
b->next = a;
bNext->prev = a;
a->prev = b;
a->next = bNext;
}else{
b->next = aNext;
a->next = bNext;
if(a->prev != NULL)
aPrev->next = b;
if(b->prev != NULL)
bPrev->next = a;
if(a->next != NULL)
aNext->prev = b;
if(bNext != NULL)
bNext->prev = a;
if(b != NULL)
b->prev = aPrev;
if(a != NULL)
a->prev = bPrev;
}
}
Following the idea that #ggorlen gave me, I rewrote the swapNodes() function adding also some new ones and finally it works perfectly. To keep track of where the nodes were before extracting them, I created a struct containing the index returned from the findIndex() function and the node itself. I also changed the findNode() function so that it returns a variable of type node* and not node**. Sure it's not very efficient, but I'll make do.
typedef struct _extractedNode{
struct _node* node;
int index;
}extractedNode;
int findIndex(node* head, node* node){
int i=1;
node* temp = head;
while(node != temp){
temp = temp->next;
i++;
}
return i;
}
extractedNode extractNode(node** head, node* node){
extractedNode extracted;
extracted.index = 0;
if(node == NULL){
printf("extractNode(): il nodo non esiste!\n");
extracted.node = NULL;
extracted.index = -1;
}else{
node* prev = node->prev;
node* next = node->next;
if(prev == NULL){
(*head) = next;
extracted.index = 1;
}
if(extracted.index != 1)
extracted.index = findIndex(*head, node);
if(prev != NULL)
prev->next = next;
if(next != NULL)
next->prev = prev;
node->next = NULL;
node->prev = NULL;
extracted.node = node;
}
return extracted;
}
void listInsertAsIndex(node** head, int index, node* node){
if(index <= 0) return;
if(index == 1) return listInsert(head, node);
else{
node* prev = findNode(*head, index-1);
node* next = prev->next;
prev->next = node;
node->prev = prev;
if(next != NULL){
node->next = next;
next->prev = node;
}
}
}
void swapNodes(node** head, node* a, node* b){
if(a == b) return;
extractedNode aX, bX;
if(a->prev == NULL && a->next == b){
aX = extractNode(head, a);
listInsertAsIndex(head, 2, aX.node);
}else if(b->prev == NULL && b->next == a){
bX = extractNode(head, b);
listInsertAsIndex(head, 2, bX.node);
}else if(a->next == b){
aX = extractNode(head, a);
listInsertAsIndex(head, aX.index +1, aX.node);
}else if(b->next == a){
bX = extractNode(head, b);
listInsertAsIndex(head, bX.index +1, bX.node);
}else{
aX = extractNode(head, a);
bX = extractNode(head, b);
if(aX.index < bX.index){
listInsertAsIndex(head, aX.index, bX.node);
listInsertAsIndex(head, bX.index +1, aX.node);
}else{
listInsertAsIndex(head, bX.index, aX.node);
listInsertAsIndex(head, aX.index, bX.node);
}
}
}

C Error: expression must have arithmetic or pointer type

typedef struct node
{
Record data;
struct node *next;
}Node;
Node *head = NULL;
void addRecord(Record x)
{
Node *previousNode = NULL;
Node *newNode;
Node *n;
newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->next = NULL;
if (head == NULL) // The list is empty
{
head = newNode;
}
else // The list is not empty
{
n = head;
while (n->next != NULL)
{
***if (n->data < newNode->data && n->next->data > newNode->data)*** // Insertion Sort
{
// We have to put it between these 2 nodes
newNode->next = n->next;
n->next = newNode;
return;
}
else
{
previousNode = n;
n = n->next;
}
}
n->next = newNode;
}
}
I have this error in the code within the if function of the insertion sort. The program says that 'n' must have arithmetic or pointer type. What seems to be the problem?
Operator overload is not supported in C, so you cannot compare Record using > operator unless it is typedefed to int or other aritimetic or pointer type.
To compare something like structures, define comparation function and use it.
Example:
typedef struct {
int a, b;
} Record;
/*
return positive value if *x > *y
return negative value if *x < *y
return 0 if *x == *y
*/
int cmpRecord(const Record* x, const Record* y) {
if (x->a + x->b > y->a + y->b) return 1;
if (x->a + x->b < y->a + y->b) return -1;
return 0;
}
/* ... */
while (n->next != NULL)
{
if (cmpRecord(&n->data, &newNode->data) < 0 && cmpRecord(&n->next->data, &newNode->data) > 0) // Insertion Sort
{
/* ... */

Implementing mergesort on a linked list

I was tasked with implementing a merge sort algorithm on a list written in C/C++. I have the general idea down, wrote my code and have successfully compiled it. However, when I run it, it will begin fine but then hang on "prepared list, now starting sort" without giving any kind of error. I have tried to look through my code but I am at a complete loss as to what the issue could be. I am also pretty amateurish with debugging, so using gdb to the best of my abilities has lead me no where. Any advice or tips would be a tremendous help, thank you all!
#include <stdio.h>
#include <stdlib.h>
struct listnode
{
struct listnode *next;
int key;
};
//Finds length of listnode
int
findLength (struct listnode *a)
{
struct listnode *temp = a;
int i = 0;
while (temp != NULL)
{
i++;
temp = temp->next;
}
return i;
}
struct listnode *
sort (struct listnode *a)
{
// Scenario when listnode is NULL
if (findLength (a) <= 1)
return a;
//Find middle
int mid = findLength (a) / 2;
struct listnode *temp = a;
struct listnode *first = a;
struct listnode *second;
for (int i = 0; i < mid - 1; i++)
{
temp = a->next;
}
second = temp->next;
temp->next = NULL;
//Recursive calls to sort lists
first = sort (first);
second = sort (second);
if (first != NULL && second != NULL)
{
if (first->key < second->key)
{
a = first;
first = first->next;
}
else
{
a = second;
second = second->next;
}
}
struct listnode *head = a;
struct listnode *tail = a;
while (first != NULL && second != NULL)
{
if (first->key < second->key)
{
tail = first;
first = first->next;
tail = tail->next;
}
else
{
tail = second;
second = second->next;
tail = tail->next;
}
}
if (first == NULL)
{
while (second != NULL)
{
tail = second;
second = second->next;
tail = tail->next;
}
}
while (first != NULL)
{
tail = first;
first = first->next;
tail = tail->next;
}
return a;
}
Here is the test code provided, written in C:int
main (void)
{
long i;
struct listnode *node, *tmpnode, *space;
space = (struct listnode *) malloc (500000 * sizeof (struct listnode));
for (i = 0; i < 500000; i++)
{
(space + i)->key = 2 * ((17 * i) % 500000);
(space + i)->next = space + (i + 1);
}
(space + 499999)->next = NULL;
node = space;
printf ("\n prepared list, now starting sort\n");
node = sort (node);
printf ("\n checking sorted list\n");
for (i = 0; i < 500000; i++)
{
if (node == NULL)
{
printf ("List ended early\n");
exit (0);
}
if (node->key != 2 * i)
{
printf ("Node contains wrong value\n");
exit (0);
}
node = node->next;
}
printf ("Sort successful\n");
exit (0);
}
You're close, but with some silly errors. Check the append operations in the merge step. They're not doing what you think they are. And of course you meant temp = temp->next; in the splitting loop.
If gdb is overwhelming, adding printf's is a perfectly fine way to go about debugging code like this. Actually you want to write a list printing function and print the sublists at each level of recursion plus the results of the merge step. It's fun to watch. Just be neat and delete all that when you're done.
Here's code that works for reference:
struct listnode *sort(struct listnode *lst) {
if (!lst || !lst->next) return lst;
struct listnode *q = lst, *p = lst->next->next;
while (p && p->next) {
q = q->next;
p = p->next->next;
}
struct listnode *mid = q->next;
q->next = NULL;
struct listnode *fst = sort(lst), *snd = sort(mid);
struct listnode rtn[1], *tail = rtn;
while (fst && snd) {
if (fst->key < snd->key) {
tail->next = fst;
tail = fst;
fst = fst->next;
} else {
tail->next = snd;
tail = snd;
snd = snd->next;
}
}
while (fst) {
tail->next = fst;
tail = fst;
fst = fst->next;
}
while (snd) {
tail->next = snd;
tail = snd;
snd = snd->next;
}
tail->next = NULL;
return rtn->next;
}
On my old MacBook this sorts 10 million random integers in a bit over 4 seconds, which doesn't seem too bad.
You can also put the append operation in a macro and make this quite concise:
struct listnode *sort(struct listnode *lst) {
if (!lst || !lst->next) return lst;
struct listnode *q = lst, *p = lst->next->next;
while (p && p->next) {
q = q->next;
p = p->next->next;
}
struct listnode *mid = q->next;
q->next = NULL;
struct listnode *fst = sort(lst), *snd = sort(mid);
struct listnode rtn[1], *tail = rtn;
#define APPEND(X) do { tail->next = X; tail = X; X = X->next; } while (0)
while (fst && snd) if (fst->key < snd->key) APPEND(fst); else APPEND(snd);
while (fst) APPEND(fst);
while (snd) APPEND(snd);
tail->next = NULL;
return rtn->next;
}
Does it have to be a top down merge sort? To get you started, here's a partial fix, didn't check for other stuff. The | if (first != NULL && second != NULL) | check isn't needed since the prior check for length <= 1 takes care of this, but it won't cause a problem.
while (first != NULL && second != NULL)
{
if (first->key < second->key)
{
tail->next = first;
tail = first;
first = first->next;
}
else
{
tail->next = second;
tail = second;
second = second->next;
}
}
if (first == NULL)
{
tail->next = second;
}
else
{
tail->next = first;
}
}

swap in doubly linked list

I am trying to swap two nodes in a doubly linked list. Below is the part of program having swap function.
int swap (int x, int y)
{
struct node *temp = NULL ;
struct node *ptr1, *ptr2;
temp = (struct node *)malloc(sizeof(struct node));
if (head == NULL )
{
printf("Null Nodes");
}
else
{
ptr1 = ptr2 = head;
int count = 1;
while (count != x)
{
ptr1 = ptr1->next;
count++;
}
int count2 = 1;
while (count2 != y)
{
ptr2 = ptr2->next;
count2++;
}
ptr1->next->prev = ptr2;
ptr1->prev->next = ptr2;
ptr2->next->prev = ptr1;
ptr2->prev->next = ptr1;
temp->prev = ptr1->prev;
ptr1->prev = ptr2->prev;
ptr2->prev = temp->prev;
temp->next = ptr1->next;
ptr1->next = ptr2->next;
ptr2->next = temp->next;
}
return 0;
}
When I run this program, in case of 1st and 2nd node, it crashes. while in case of any other nodes, it gives infinite loop output. (eg:- 2->4 2->4 2->4....so on)`.
I know there are some more questions about node swappings, but I didn't find any one similar to my problem. Please help me out..!!
Thanks in Advance.
The code will fail if ptr1 == head (ptr1->prev == NULL) or ptr2 == head (ptr2->prev == NULL), because it ends up trying to use head->next, which doesn't exist. There also needs to be a check for the end of a list, if ptr1->next == NULL or ptr2->next == NULL, which can be handled using a local tail pointer. Using pointers to pointer to node can simplify the code. For example the pointer to next pointer to ptr1 could be &ptr1->prev->next or &head. The pointer to prev pointer to ptr2 could be &ptr2->next->prev or &tail (and set tail = ptr2).
Using pointers to pointer to node fixes the issue with swapping adjacent nodes. Also temp can be a pointer to node.
Example code using pointers to nodes (instead of counts) to swap:
typedef struct node NODE;
/* ... */
NODE * SwapNodes(NODE *head, NODE *ptr1, NODE *ptr2)
{
NODE **p1pn; /* & ptr1->prev->next */
NODE **p1np; /* & ptr1->next->prev */
NODE **p2pn; /* & b->prev->next */
NODE **p2np; /* & b->next->prev */
NODE *tail; /* only used when x->next == NULL */
NODE *temp; /* temp */
if(head == NULL || ptr1 == NULL || ptr2 == NULL || ptr1 == ptr2)
return head;
if(head == ptr1)
p1pn = &head;
else
p1pn = &ptr1->prev->next;
if(head == ptr2)
p2pn = &head;
else
p2pn = &ptr2->prev->next;
if(ptr1->next == NULL){
p1np = &tail;
tail = ptr1;
} else
p1np = &ptr1->next->prev;
if(ptr2->next == NULL){
p2np = &tail;
tail = ptr2;
}else
p2np = &ptr2->next->prev;
*p1pn = ptr2;
*p1np = ptr2;
*p2pn = ptr1;
*p2np = ptr1;
temp = ptr1->prev;
ptr1->prev = ptr2->prev;
ptr2->prev = temp;
temp = ptr1->next;
ptr1->next = ptr2->next;
ptr2->next = temp;
return head;
}
This can be compacted, but if you are having problems, it can help to spell it out in detail.
typedef struct node Node;
void link( Node* a, Node* b )
{
a->next = b;
b->prev = a;
}
void swap_nodes( Node* a, Node* b )
{
if(a==b) return; // don't swap with yourself
// handle adjacent nodes separately
if( a->next == b )
{
Node* bef = a->prev;
Node* aft = b->next;
link( bef, b); // link bef, b, a, aft
link( b, a );
link( a, aft );
}
else if( b->next == a )
{
Node* bef = b->prev;
Node* aft = a->next;
link( bef, a); // link bef, a, b, aft
link( a, b );
link( b, aft );
}
else
{
Node* a_prv = a->prev;
Node* a_nxt = a->next;
Node* b_prv = b->prev;
Node* b_nxt = b->next;
link( a_prv, b ); link( b, a_nxt ); // links b in a's old position
link( b_prv, a ); link( a, b_nxt ); // links a in b's old position
}
}
Also note that your head node should never be null, it should be a sentry node that links to itself if your list is empty. This means that there are never a first node, nor a last, nor is the list ever empty. This removes a ton of special cases. See here

Resources