Write a c program to reverse singly link list?  this is one of the famous interview question. There are various linked list data structure in computer science which are used to store data. the data is grouped with the address of next data and this group identity is called node in linked list. As from below figure the list is 1,2,3,4,5 and 5 is the last node of the link list.

 revlinkl

         (Each node in above is having address of its next node , for example head node in above list , is having address of node containing number 2)

Before:

Head(1)->(2)->(3)->(4)->(5)Tail

After:

Tail(1)<-(2)<-(3)<-(4)<-(5)Head

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

// data structure for link list
typedef struct list {
	int data; //data
	struct list *next; // point to next list
} list;

list *head = NULL;

void insertData(int a);
void printList(list * head);
list* reverseList(list * head);

int main() {

	int a = 0;
	int i = 0;
	for (i = 0; i < 6; i++) {
		printf("Enter your data :");
		scanf("%d", &a);
		insertData(a);
	}
	// print
	printList(head);
	list *h = reverseList(head);
	printList(h);
	return 0;
}

void insertData(int a) {
	// create first node
	if (head == NULL) {
		head = (list *) malloc(sizeof(list));
		head->data = a;
		head->next = NULL;
	} else {
		// go to last node
		list *p = head;

		while (p->next != NULL)
			p = p->next;
		// create new node
		list *new_one = (list *) malloc(sizeof(list));
		new_one->data = a;
		p->next = new_one;
		new_one->next = NULL;
	}
}

list* reverseList(list * head)
{
	if (head == 0)
		return NULL;
	if (head->next == 0)
		return NULL;

	list *current = head;
	list *prev = NULL;

	while (current != NULL)
	{
		list *next = current->next; // save next node
		current->next = prev;
    	prev = current;
		current = next;
	}
	head = prev;
	return head;
}

void printList(list * head) {
	list *p = head;
	if (p == NULL) {
		printf("list is empty\n");
		return;
	}
	while (p != NULL) {
		printf("%d ", p->data);
		p = p->next;
	}
	printf("\n");
	return;
}

 



Related Contents to follow