Create Singly Linked List

Create a structure for node.see below code

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

Create a head pointer that represents address of initial element in the list. When the list is empty who's value is NULL.

struct node *head=NULL;

Now, the following create() function is creates a list with required number of nodes.

void create(){
  int ch;
  struct node *newNode,*lastNode;
  lastNode=(struct node*)malloc(sizeof(struct node*));
  do{
    newNode=(struct node*)malloc(sizeof(struct node*));
    printf("Enter node value:\n");
    scanf("%d",&newNode->data);
    if(head==NULL)
      head=newNode;
    lastNode->next=newNode;
    lastNode=newNode;
    printf("To continue press 1 otherwise 0:\n");
    scanf("%d",&ch);
  }while(ch==1);
  lastNode->next=NULL;
}

Finally, display list with traverse() function.

void traverse(){
  struct node *ptr;
  if(head==NULL){
    printf("List is empty.\n");
  }else{
    ptr=head;
    while(ptr!=NULL){
      printf("%d->",ptr->data);
      ptr=ptr->next;
    }
    printf("NULL");
  }
}


Click on the below button for implementation of Singly Linked List with it's operations.

Singly Linked List



Related Programs


  1. Create Singly Linked List with N number of nodes and display.
  2. Perform insertion operation on Singly Linked List.
  3. Perform deletion operation on Singly Linked List.
  4. Reverse of Singly Linked List.
  5. Move last node of Singly Linked List to first.
  6. Swap first and last nodes in a Singly Linked List.
  7. Find the length of Singly Linked List.
  8. Find middle node of Singly Linked List

No comments:

Post a Comment

Total Pageviews