Rabu, Mei 29, 2013

C: Linked List & Interchange (Swap)

Soalan :
Write a C program to create a linked list and interchange the elements to the list at position  'm' and 'n' and display contents of the list before and after interchanging the elements.

Jawapan:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

struct link
{
 int data;
 struct link *next;
};
struct link *start=NULL;

void create();
void display();
void swap();

void main()
{
 int ch;
 do
 {
  printf("\n\n--------Main Menu--------");
  printf("\n1. Create");
  printf("\n2. Swap");
  printf("\n3. Exit");
  printf("\n\nEnter Your Choice >>");
  scanf("%d",&ch);
  switch(ch)
  {
   case 1:
    create(); 
    display();
    break;
   case 2:
    swap();
    display();
    break;
   case 3:
    exit(0);
    break;
   default:
    printf("\nInvalid Choice... Try Again");
    getch();
  }/*End of switch*/
 }while(ch!=3);/*End of while loop*/
}/*End of void main()*/
void create()
{
 struct link *p,*node;
 printf("\nEnter Data >> ");
 p=(struct link*)malloc(sizeof(struct link));
 scanf("%d",&p->data);
 p->next=NULL;
 if(start==NULL)
 start=p;
 else
 {
  node=start;
  while(node->next!=NULL)
  node=node->next;
  node->next=p;
 }/*End of else*/
}/*End of void create()*/

void display()
{
 struct link *node;
 if(start==NULL)
 {
  printf("\nList Is Empty");
  getch();
 }/*End of if*/
 node=start;
 while(node!=NULL)
 {
  printf("%d ",node->data);
  node=node->next;
 }/*End of while loop*/
 getch();
}/*End of void display()*/
void swap()
{
 int m,n,i;
 struct link *node1,*node2;
 if(start==NULL)
 {
  printf("\nList Is Empty");
 }/*End of if*/
 node1=start;
 printf("\nEnter Mth Position >> ");
 scanf("%d",&m);
 for(i=0;i< m;i++)
 {
  node1=node1->next;
  if(node1==NULL)
  {
   printf("\nWrong Location Enterred..");
  }/*End of if*/
 }/*End of i for loop*/
 printf("\nEnter Nth Position >> ");
 scanf("%d",&n);
 node2=start;
 for(i=0;i< n;i++)
 {
  node2=node2->next;
  if(node2==NULL)
  {
   printf("\nWrong Location Enterred..");
  }/*End of if*/
 }/*End of i for loop*/
 node1->data=(node1->data)+(node2->data)-((node2->data)=(node1->data));
 printf("\nElement Swapped\n");
}

0 ulasan:

Catat Ulasan

Pesanan daripada penulis :
Selamat datang ke 0x2013LΣΣT. Sekiranya anda mempunyai persoalan, pandangan, permintaan, bantuan, cadangan dan sebagainya. Tinggalkan pesanan anda ke dalam kotak komen. Terima kasih !
- http://0x2013.blogspot.com -