Tuesday 14 June 2016

Swap linked list node without swapping data

swapnode.c
#include <stdio.h>
#include <stdlib.h>

struct node {
        int             data;
        struct node *next;
};

void AppendToList (struct node **head, int value)
{
        struct node *newNode = NULL;

        newNode = (struct node *) malloc(sizeof(struct node));
        if (newNode == NULL)
                return;

        newNode->data = value;
        newNode->next = NULL;

        if (*head == NULL)
                        *head = newNode;
        else {
                newNode->next = *head;
                *head   = newNode;
        }

        return;
}

void PrintList (struct node **head)
{
        struct node *temp = *head;

        while (temp) {
                printf("%d\r\n", temp->data);
                temp = temp->next;
        }

        return;
}

void swapNodes (struct node **head, int a, int b)
{
        struct node *prev_x, *curr_x;
        struct node *prev_y, *curr_y, *temp;

        curr_x = *head;
        while (curr_x && (curr_x->data != a)) {
                prev_x = curr_x;
                curr_x = curr_x->next;
        }

        curr_y = *head;
        while (curr_y && (curr_y->data != b)) {
                prev_y = curr_y;
                curr_y = curr_y->next;
        }

        prev_x->next = curr_y;
        temp                             = curr_y->next;
        curr_y->next = curr_x->next;

        prev_y->next = curr_x;
        curr_x->next = temp;

        return;
}


int main(int argc, char *argv[])
{
        int i;
        struct node *head = NULL;

        if (argc <= 2) {
                printf("usage: ./swapnode <a> <b> \r\n");
                return 0;
        }

        for (i = 1; i <= 10; i++) {
                AppendToList(&head, i);
        }

        printf("List\r\n");
        PrintList(&head);

        swapNodes(&head, atoi(argv[1]), atoi(argv[2]));
        printf("After swap\r\n");
        PrintList(&head);

        return 0;
}



CC = gcc

CFLAGS = -g -Wall

all : swapnode
swapnode: swapnode.o
        ${CC} ${CFLAGS} -o $@ swapnode.o

clean:
        -@rm *.o

No comments:

Post a Comment