Saturday, January 25, 2020

Posted on Leave a Comment

Concatenation of two singly linked list

A ‘C’ program to create two singly linked lists and concatenate one list at the end of another list.

Concatenation of two singly linked list


Source code


#include 

#include 

#include 

#include 

#include 

struct linear_list {
  int info;
  struct linear_list * next;
}* start, * start1, * newnode, * ptr;

void main() {
  int item;
  int i;
  char ch;
  clrscr();
  printf(“\nCreate first linked list: \n”);
  newnode = (struct linear_list * ) malloc(sizeof(struct linear_list));
  start = newnode;
  do {
    printf(“\nEnter data: “);
    scanf(“ % d”, & item);
    newnode - > info = item;
    printf(“\nDo you want to create another node: (y / n)”);
    fflush(stdin);
    scanf(“ % c”, & ch);
    if (tolower(ch) == ’y’) {
      newnode - > next = (struct linear_list * ) malloc(sizeof(struct linear_list));
      newnode = newnode - > next;
    } else {
      newnode - > next = NULL;
    }
  } while (tolower(ch) != ’n’);
  clrscr();
  printf(“\nCreate second linked list: \n”);
  newnode = (struct linear_list * ) malloc(sizeof(struct linear_list));
  start1 = newnode;
  do {
    printf(“\nEnter data: “);
    scanf(“ % d”, & item);
    newnode - > info = item;
    printf(“\nDo you want to create another node: (y / n)”);
    fflush(stdin);
    scanf(“ % c”, & ch);
    if (tolower(ch) == ’y’) {
      newnode - > next = (struct linear_list * ) malloc(sizeof(struct linear_list));
      newnode = newnode - > next;
    } else {
      newnode - > next = NULL;
    }
  } while (tolower(ch) != ’n’);
  ptr = start;
  while (ptr - > next != NULL) {
    ptr = ptr - > next;
  }
  ptr - > next = start1;
  printf(“\n Concatenated Linked Lists are: \n”);
  ptr = start;
  i = 1;
  while (ptr != NULL) {
    printf(“\nNode % d: % d”, i, ptr - > info);
    ptr = ptr - > next;
    i++;
  }
  getch();
}

Output

Create first linked list:

Enter data: 2

Do you want to create another node:(y/n)y

Enter data: 8

Do you want to create another node:(y/n)y

Enter data: 10

Do you want to create another node:(y/n)n

Create second linked list:

Enter data: 5

Do you want to create another node:(y/n)y

Enter data: 7

Do you want to create another node:(y/n)y

Enter data: 34

Do you want to create another node:(y/n)n

Concatenated Linked Lists are:

Node 1 : 2
Node 2 : 8
Node 3 : 10
Node 4 : 5
Node 5 : 7
Node 6 : 34

0 comments:

Post a Comment

Codearea.in is featured by projectsgeek.com. Powered by Blogger.