Monday 9 May 2016

Linked List Insertion at the beginning .


Linked List Insertion, A node can be added in three ways:
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list.

* Insertion at the beginning of the Singly linked lists  :
  • C / C++ :
/*
@author Anurag Goel
Inserting at beginning and Traversing the elements of linked list.
*/
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
int main() {
struct Node {
    int data;
    Node * next;
    };
    char choice;
    Node * head, * tail, * temp;
    head = NULL;
    do {
        printf("Enter a element to insert.");
        temp = (Node * ) malloc(sizeof(Node));
        scanf("%d", & temp -> data);
        if (head == NULL) {
            tail = head = temp;
            head -> next = NULL;
        } else {
            temp -> next = head;
            head = temp;
        }
        fflush(stdin);
        printf("Do you want to continue (Y) or (N)");
        scanf("%c", & choice);
    } while ((choice == 'Y') || (choice == 'y'));
    printf("Linked List after insertion is : ");
    temp = head;
    while (temp != NULL) {
       printf("%d", temp -> data);
        temp = temp -> next;
    }
    getch();
    return 0;
    }
 

  • JAVA  : 

/*
@author Anurag Goel
Inserting at beginning and Traversing the elements of linked list.
*/
class InsertAtBegin {
 static class Node {
  int data;
  Node next;
 }
 public static void main(String args[]) {
  Node node = insert(insert(insert(null, 1), 2), 3);
  printList(node);

 }

 public static Node insert(Node head, int data) {
  if (head == null) {
   Node node = new Node();
   node.data = data;
   node.next = null;
   return node;
  }
  Node node = new Node();
  node.data = data;
  node.next = head;
  return node;

 }
 public static void printList(Node node) {
  Node currentNode = node;
  while (currentNode != null) {
   System.out.println(currentNode.data);
   currentNode = currentNode.next;
  }

 }

  • ·        Python :

__author__ = 'Anurag Goel'
class Node:
    def init(self):
        self.data=None
        self.next=None
       
def insert(head,data) :
    if head==None :
        node = Node()
        node.data=data
        node.next=None;
        return node;
    else :
        node = Node()
        node.data=data;
        node.next=head;
        return node
   
head = insert(insert(insert(None, 1), 2), 3);
print "Elements In Linked List After Insertion : "
currentNode= head;
while(currentNode!=None):
    print currentNode.data
    currentNode=currentNode.next

No comments:

Post a Comment