Linked list

A linked list is a way to store a collection of elements. Like an array these can be character or integers. Each element in a linked list is stored in the form of a node.

A node is a collection of two sub-elements or parts. A data part that stores the element and a next part that stores the link to the next node.

A linked list is formed when many such nodes are linked together to form a chain. Each node points to the next node present in the order. The first node is always used as a reference to traverse the list and is called HEAD. The last node points to NULL.

Declaring a Linked list :

In C language, a linked list can be implemented using structure and pointers .

struct LinkedList{

    int data;

    struct LinkedList *next;

 };

The above definition is used to create every node in the list. The data field stores the element and the next is a pointer to store the address of the next node.

Reverse a linked list

initialize three pointers prev as NULL, curr as head and next as NULL.

Iterate trough the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next

// Now change next of current
// This is where actual reversing happens
curr->next = prev

// Move prev and curr one step forward
prev = curr
curr = next

#include<stdio.h>

#include<stdlib.h>

struct node

{

    int data;

    struct node*link;

};

struct node*root=NULL;

void Append(void);

void reverse (void)

{

    struct node*temp = NULL,*temp1 = NULL;

    while(root) {

        temp1 = root->link;

        root->link = temp;

        temp = root;

        root = temp1;

    }

    struct node*p = temp;

    while(p) {

        printf("%d--->%p---->",p->data,&p->data);

       p = p->link;

    }

}

int main()

{

    while(1)

    {

        int ch;

        printf("1.Append:\n");

        printf("7.reverse:\n");

        printf("8.Quit:\n");

 

        printf("Enter the choice:\n");

        scanf("%d",&ch);

        switch(ch)

        {

            case 1 : Append();

                        break;

            case 2 : reverse();

                        break;

            case 3 : exit(1);

                        break;

            default : printf("Invalid choice\n");

        }

    }

}

void Append (void)

{

    struct node*temp;

    temp=(struct node*)malloc(sizeof(struct node));

    printf("enter the node value:\n");

    scanf("%d",&temp->data);

    temp->link=NULL;

    if(root==NULL)  {   //list is empty

        root=temp; }

    else{

        struct node*p;

        p=root;

        while(p->link!=NULL) {

            p=p->link;}

        p->link=temp;

}

}