C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include #include // A Linked List Node struct Node { int data; struct Node* next; }; // Helper function to print a given linked list void printList[struct Node* head] { struct Node* temp = head; while [temp] { printf["%d —> ", temp->data]; temp = temp->next; } printf["NULL"]; } int main[void] { struct Node e = { 5, NULL };// last node struct Node d = { 4, &e }; struct Node c = { 3, &d }; struct Node b = { 2, &c }; struct Node a = { 1, &b };// first node struct Node* head = &a; printList[head]; return 0; } |
DownloadRun Code
Output:
1 —> 2 —> 3 —> 4 —> 5 —> NULL
Linked List | Set 1 [Introduction]
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers.
Why Linked List?
Arrays can be used to store linear data of similar types, but arrays have the following limitations.
1] The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage.
2] Inserting a new element in an array of elements is expensive because the room has to be created for the new elements and to create room existing elements have to be shifted but in Linked list if we have the head node then we can traverse to any node through it and insert new node at the required position.
For example, in a system, if we maintain a sorted list of IDs in an array id[].
id[] = [1000, 1010, 1050, 2000, 2040].
And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 [excluding 1000].
Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved due to this so much work is being done which affects the efficiency of the code.
Advantages over arrays
1] Dynamic size
2] Ease of insertion/deletion
Drawbacks:
1] Random access is not allowed. We have to access elements sequentially starting from the first node[head node]. So we cannot do binary search with linked lists efficiently with its default implementation. Read about it here.
2] Extra memory space for a pointer is required with each element of the list.
3] Not cache friendly. Since array elements are contiguous locations, there is locality of reference which is not there in case of linked lists.
Representation:
A linked list is represented by a pointer to the first node of the linked list. The first node is called the head. If the linked list is empty, then the value of the head points to NULL.
Each node in a list consists of at least two parts:
1] data[we can store integer, strings or any type of data].
2] Pointer [Or Reference] to the next node[connects one node to another]
In C, we can represent a node using structures. Below is an example of a linked list node with integer data.
In Java or C#, LinkedList can be represented as a class and a Node as a separate class. The LinkedList class contains a reference of Node class type.
C
// A linked list node struct Node { int data; struct Node* next; }; |
C++
class Node { public: int data; Node* next; }; |
Java
class LinkedList { Node head; // head of the list /* Linked list Node*/ class Node { int data; Node next; // Constructor to create a new node // Next is by default initialized // as null Node[int d] { data = d; } } } |
Python
# Node class class Node:
# Function to initialize the node object def __init__[self, data]: self.data = data # Assign data self.next = None # Initialize # next as null
# Linked List class class LinkedList:
# Function to initialize the Linked # List object def __init__[self]: self.head = None |
C#
class LinkedList { // The first node[head] of the linked list // Will be an object of type Node [null by default] Node head; class Node { int data; Node next; // Constructor to create a new node Node[int d] { data = d; } } } |
Javascript
var head; // head of the list /* Linked list Node*/ class Node {
// Constructor to create a new node // Next is by default initialized // as null constructor[val] { this.data = val; this.next = null; } } // This code is contributed by gauravrajput1 |
First Simple Linked List in C Let us create a simple linked list with 3 nodes.
C++
// A simple CPP program to introduce // a linked list #include using namespace std; class Node { public: int data; Node* next; }; // Program to create a simple linked // list with 3 nodes int main[] { Node* head = NULL; Node* second = NULL; Node* third = NULL; // allocate 3 nodes in the heap head = new Node[]; second = new Node[]; third = new Node[]; /* Three blocks have been allocated dynamically. We have pointers to these three blocks as head, second and third head second third | | | | | | +---+-----+ +----+----+ +----+----+ | # | # | | # | # | | # | # | +---+-----+ +----+----+ +----+----+
# represents any random value. Data is random because we haven’t assigned anything yet */ head->data = 1; // assign data in first node head->next = second; // Link first node with // the second node /* data has been assigned to the data part of first block [block pointed by the head]. And next pointer of the first block points to second. So they both are linked. head second third | | | | | | +---+---+ +----+----+ +-----+----+ | 1 | o----->| # | # | | # | # | +---+---+ +----+----+ +-----+----+ */ // assign data to second node second->data = 2; // Link second node with the third node second->next = third; /* data has been assigned to the data part of the second block [block pointed by second]. And next pointer of the second block points to the third block. So all three blocks are linked.
head second third | | | | | | +---+---+ +---+---+ +----+----+ | 1 | o----->| 2 | o-----> | # | # | +---+---+ +---+---+ +----+----+ */ third->data = 3; // assign data to third node third->next = NULL; /* data has been assigned to the data part of the third block [block pointed by third]. And next pointer of the third block is made NULL to indicate that the linked list is terminated here. We have the linked list ready. head | | +---+---+ +---+---+ +----+------+ | 1 | o----->| 2 | o-----> | 3 | NULL | +---+---+ +---+---+ +----+------+
Note that only the head is sufficient to represent the whole list. We can traverse the complete list by following the next pointers. */ return 0; } // This code is contributed by rathbhupendra |
C
// A simple C program to introduce // a linked list #include #include struct Node { int data; struct Node* next; }; // Program to create a simple linked // list with 3 nodes int main[] { struct Node* head = NULL; struct Node* second = NULL; struct Node* third = NULL; // allocate 3 nodes in the heap head = [struct Node*]malloc[sizeof[struct Node]]; second = [struct Node*]malloc[sizeof[struct Node]]; third = [struct Node*]malloc[sizeof[struct Node]]; /* Three blocks have been allocated dynamically. We have pointers to these three blocks as head, second and third head second third | | | | | | +---+-----+ +----+----+ +----+----+ | # | # | | # | # | | # | # | +---+-----+ +----+----+ +----+----+
# represents any random value. Data is random because we haven’t assigned anything yet */ head->data = 1; // assign data in first node head->next = second; // Link first node with // the second node /* data has been assigned to the data part of the first block [block pointed by the head]. And next pointer of first block points to second. So they both are linked. head second third | | | | | | +---+---+ +----+----+ +-----+----+ | 1 | o----->| # | # | | # | # | +---+---+ +----+----+ +-----+----+ */ // assign data to second node second->data = 2; // Link second node with the third node second->next = third; /* data has been assigned to the data part of the second block [block pointed by second]. And next pointer of the second block points to the third block. So all three blocks are linked.
head second third | | | | | | +---+---+ +---+---+ +----+----+ | 1 | o----->| 2 | o-----> | # | # | +---+---+ +---+---+ +----+----+ */ third->data = 3; // assign data to third node third->next = NULL; /* data has been assigned to data part of third block [block pointed by third]. And next pointer of the third block is made NULL to indicate that the linked list is terminated here. We have the linked list ready. head | | +---+---+ +---+---+ +----+------+ | 1 | o----->| 2 | o-----> | 3 | NULL | +---+---+ +---+---+ +----+------+
Note that only head is sufficient to represent the whole list. We can traverse the complete list by following next pointers. */ return 0; } |
Java
// A simple Java program to introduce a linked list class LinkedList { Node head; // head of list /* Linked list Node. This inner class is made static so that main[] can access it */ static class Node { int data; Node next; Node[int d] { data = d; next = null; } // Constructor } /* method to create a simple linked list with 3 nodes*/ public static void main[String[] args] { /* Start with the empty list. */ LinkedList llist = new LinkedList[]; llist.head = new Node[1]; Node second = new Node[2]; Node third = new Node[3]; /* Three nodes have been allocated dynamically. We have references to these three blocks as head, second and third llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | null | | 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ */ llist.head.next = second; // Link first node with the second node /* Now next of the first Node refers to the second. So they both are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ */ second.next = third; // Link second node with the third node /* Now next of the second Node refers to third. So all three nodes are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o-------->| 3 | null | +----+------+ +----+------+ +----+------+ */ } } |
Python
# A simple Python program to introduce a linked list # Node class class Node: # Function to initialise the node object def __init__[self, data]: self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__[self]: self.head = None # Code execution starts here if __name__=='__main__': # Start with the empty list llist = LinkedList[] llist.head = Node[1] second = Node[2] third = Node[3] ''' Three nodes have been created. We have references to these three blocks as head, second and third llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | None | | 2 | None | | 3 | None | +----+------+ +----+------+ +----+------+ ''' llist.head.next = second; # Link first node with second ''' Now next of first Node refers to second. So they both are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ ''' second.next = third; # Link second node with the third node ''' Now next of second Node refers to third. So all three nodes are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o-------->| 3 | null | +----+------+ +----+------+ +----+------+ ''' |
C#
// A simple C# program to introduce a linked list using System; public class LinkedList { Node head; // head of list /* Linked list Node. This inner class is made static so that main[] can access it */ public class Node { public int data; public Node next; public Node[int d] { data = d; next = null; } // Constructor } /* method to create a simple linked list with 3 nodes*/ public static void Main[String[] args] { /* Start with the empty list. */ LinkedList llist = new LinkedList[]; llist.head = new Node[1]; Node second = new Node[2]; Node third = new Node[3]; /* Three nodes have been allocated dynamically. We have references to these three blocks as head, second and third llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | null | | 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ */ llist.head.next = second; // Link first node with the second node /* Now next of first Node refers to second. So they both are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | null | | 3 | null | +----+------+ +----+------+ +----+------+ */ second.next = third; // Link second node with the third node /* Now next of the second Node refers to third. So all three nodes are linked. llist.head second third | | | | | | +----+------+ +----+------+ +----+------+ | 1 | o-------->| 2 | o-------->| 3 | null | +----+------+ +----+------+ +----+------+ */ } } // This code has been contributed by 29AjayKumar |
Linked List Traversal
In the previous program, we have created a simple linked list with three nodes. Let us traverse the created list and print the data of each node. For traversal, let us write a general-purpose function printList[] that prints any given list.
Difference between a Static Queue and a Singly Linked List
Static Queue: A queue is an ordered list of elements. It always works in first in first out[FIFO] fashion. All the elements get inserted at the REAR and removed from the FRONT of the queue. In implementation of the static Queue, an array will be used so all operation of queue are index based which makes it faster for all operations except deletion because deletion requires shifting of all the remaining elements to the front by one position.
A Static Queue is a queue of fixed size implemented using array.
Singly Linked List: A linked list is also an ordered list of elements. You can add an element anywhere in the list, change an element anywhere in the list, or remove an element from any position in the list. Each node in the list stores the content and a pointer or reference to the next node in the list. To store a single linked list, only the reference or pointer to the first node in that list must be stored. The last node in a single linked list points to nothing [or null].
Here are some of the major differences between a Static Queue and a Singly Linked List
Below is the implementation of a Static Queue:
Java
// Java program to implement a queue using an array class Queue { private static int front, rear, capacity; private static int queue[]; Queue[int c] { front = rear = 0; capacity = c; queue = new int[capacity]; } // function to insert an element // at the rear of the queue static void queueEnqueue[int data] { // check queue is full or not if [capacity == rear] { System.out.printf["\nQueue is full\n"]; return; } // insert element at the rear else { queue[rear] = data; rear++; } return; } // function to delete an element // from the front of the queue static void queueDequeue[] { // if queue is empty if [front == rear] { System.out.printf["\nQueue is empty\n"]; return; } // shift all the elements from index 2 till rear // to the right by one else { for [int i = 0; i < rear - 1; i++] { queue[i] = queue[i + 1]; } // store 0 at rear indicating there's no element if [rear < capacity] queue[rear] = 0; // decrement rear rear--; } return; } // print queue elements static void queueDisplay[] { int i; if [front == rear] { System.out.printf["\nQueue is Empty\n"]; return; } // traverse front to rear and print elements for [i = front; i < rear; i++] { System.out.printf[" %d "]; disp = disp.next; } } // function to return the total nodes in the list int Count[] { int elements = 0; Node count = head; while [count != null] { count = count.next; elements++; } return elements; } } public class GFG { // Driver code public static void main[String[] args] throws Exception { // create object of class singlyList SinglyLList list = new SinglyLList[]; // insert elements of singly linked list // at beginning list.InsertAtStart[3]; list.InsertAtStart[2]; list.InsertAtStart[1]; // print linked list elements list.Display[]; // insert element at the end of list list.InsertAtLast[1]; System.out.println["\nafter inserting node at the end\n "]; // print linked list elements list.Display[]; // delete an element at the given position list.DeleteAtPos[1]; // delete starting element list.DeleteAtStart[]; // delete last element list.DeleteAtLast[]; System.out.println["\nafter deleting node: second, first and last\n "]; // print linked list elements list.Display[]; } } |
C#
// C# program to implement singly linked list using System; public class SinglyLList { public class Node { // node variables public int data; public Node next; public Node[int data] { this.data = data; this.next = null; } } // create reference variable of Node public Node head; // function to insert a node // at the beginning of the list public void InsertAtStart[int data] { // create a node Node new_node = new Node[data]; new_node.next = head; head = new_node; } // function to insert node // at the end of the list public void InsertAtLast[int data] { Node new_node = new Node[data]; if [head == null] { head = new_node; return; } new_node.next = null; Node last = head; while [last.next != null] { last = last.next; } last.next = new_node; } // function to delete a node // at the beginning of the list public void DeleteAtStart[] { if [head == null] { Console.WriteLine["List is empty"]; return; } head = head.next; } // function to delete a node at // a given position in the list public void DeleteAtPos[int pos] { int position = 0; if [pos > Count[] || pos < 0] { throw new Exception["Incorrect position exception"]; } Node temp = head; while [position != pos - 1] { temp = temp.next; position++; } temp.next = temp.next.next; } // function to delete a node // from the end of the list public void DeleteAtLast[] { Node delete = head; while [delete.next != null && delete.next.next != null] { delete = delete.next; } delete.next = null; } // function to display all the nodes of the list public void Display[] { Node disp = head; while [disp != null] { Console.Write[disp.data + "->"]; disp = disp.next; } } // function to return the total nodes in the list public int Count[] { int elements = 0; Node count = head; while [count != null] { count = count.next; elements++; } return elements; } } class GFG { // Driver code public static void Main[String[] args] { // create object of class singlyList SinglyLList list = new SinglyLList[]; // insert elements of singly linked list // at beginning list.InsertAtStart[3]; list.InsertAtStart[2]; list.InsertAtStart[1]; // print linked list elements list.Display[]; // insert element at the end of list list.InsertAtLast[1]; Console.WriteLine["\nafter inserting node at the end\n "]; // print linked list elements list.Display[]; // delete an element at the given position list.DeleteAtPos[1]; // delete starting element list.DeleteAtStart[]; // delete last element list.DeleteAtLast[]; Console.WriteLine["\nafter deleting node: second, first and last\n "]; // print linked list elements list.Display[]; } } // This code has been contributed by 29AjayKumar |
Javascript
// JavaScript program to implement // singly linked list class Node { constructor[val] { this.data = val; this.next = null; } } // create reference variable of Node var head; // function to insert a node // at the beginning of the list function InsertAtStart[data] { // create a node var new_node = new Node[data]; new_node.next = head; head = new_node; } // function to insert node // at the end of the list function InsertAtLast[data] { var new_node = new Node[data]; if [head == null] { head = new_node; return; } new_node.next = null; var last = head; while [last.next != null] { last = last.next; } last.next = new_node; } // function to delete a node // at the beginning of the list function DeleteAtStart[] { if [head == null] { document.write["List is empty"]; return; } head = head.next; } // function to delete a node at // a given position in the list function DeleteAtPos[pos] { var position = 0; if [pos > Count[] || pos < 0] {
} var temp = head; while [position != pos - 1] { temp = temp.next; position++; } temp.next = temp.next.next; } // function to delete a node // from the end of the list function DeleteAtLast[] { var deletenode = head; while [deletenode.next != null && deletenode.next.next != null] { deletenode = deletenode.next; } deletenode.next = null; } // function to display all the nodes of the list function Display[] { var disp = head; while [disp != null] { document.write[disp.data + "->"]; disp = disp.next; } } // function to return the total nodes in the list function Count[] { var elements = 0; var count = head; while [count != null] { count = count.next; elements++; } return elements; }
// Driver code // create object of class singlyList
// insert elements of singly linked list // at beginning InsertAtStart[3]; InsertAtStart[2]; InsertAtStart[1]; // print linked list elements Display[]; // insert element at the end of list InsertAtLast[1]; document.write[
" ]; // print linked list elements Display[]; // delete an element at the given position DeleteAtPos[1]; // delete starting element DeleteAtStart[]; // delete last element DeleteAtLast[]; document.write[
" ]; // print linked list elements Display[]; // This code is contributed by todaysgaurav |
Output: 1->2->3-> after inserting node at the end 1->2->3->1-> after deleting node: second, first and last 3->
Article Tags :
Linked List
Queue
Technical Scripter
Arrays
Technical Scripter 2018
Practice Tags :
Linked List
Arrays
Queue
Read Full Article
C language to achieve the method of static linked list
Before I started, I thought that there was no difference between a static list and a dynamic list. On second thought, I found that there was a topic of memory management hidden in the static list.
The word "static" in a static linked list refers to the source of memory as static memory [usually a global array]. Unlike dynamic linked list, in a static linked list nodes in memory the application for and release of all need to maintain, because here is the list, it is easy to think of will spare node link form a free_list, each time need from free_list head a node, is released to the node to the head, so that it can very easy to the realization of the list of other operations.
//Static linked list implementation #include #define MAXN 16 // capacity of list. typedef int element; // element type. // define boolean type: typedef int bool; #define true -1 #define false 0 #define NPTR -1 // null pointer definition. can not between 0 to MAXN-1. typedef int pointer; #define DEBUGVAL[x] printf["%s: %dn", #x, [x]]; // a macro for debug. struct __node { element data; pointer next; }SLList[MAXN]; pointer ifree, idata; #define nextof[p] SLList[p].next #define dataof[p] SLList[p].data #define _alloc[d] ifree; dataof[ifree]=[d]; ifree != NPTR ? ifree=nextof[ifree] : NPTR #define _free[p] nextof[p]=ifree; ifree = p void init[] { int i; ifree = 0; idata = NPTR; for[ i=0; i < MAXN-1; i++] nextof[i] = i+1; nextof[i] = NPTR; } // clear all nodes. void clear[] { init[]; } // push val to front. bool push_front[element val] { pointer tmp, np; if[ ifree != NPTR ] { np = _alloc[val]; nextof[np] = idata; idata = np; return true; } return false; } // push val to end of list. bool push_back[element val] { if[ idata == NPTR ] { //Empty table, write directly idata = _alloc[val]; nextof[idata] = NPTR; return true; } if[ ifree != NPTR ] { //Not empty, find the last node first pointer last = idata, np; while[ nextof[last] != NPTR ] last = nextof[last]; np = _alloc[val]; nextof[np] = NPTR; nextof[last] = np; return true; } return false; } // insert val to after p pointed node. bool insert_after[pointer p, element val] { if[ ifree != NPTR && p != NPTR ] { pointer pn = _alloc[val]; nextof[pn] = nextof[p]; nextof[p] = pn; return true; } return false; } // insert to the position in front of p. bool insert[pointer ptr, element val] { if[ ifree == NPTR ] return false; //No nodes, just return if[ ptr == idata ] { //There is a node pointer np = _alloc[val]; nextof[np] = idata; idata = np; return true; } else { //In other cases, find the precursor of PTR and insert it pointer p = idata; while[ p != NPTR ] { if[ nextof[p] == ptr ] { // find p -- the prev node of ptr. return insert_after[p, val]; // insert val after p. } p = nextof[p]; } } return false; } // find element, return the prev node pointer. pointer find_prev[element val] { pointer p = idata; while[ p != NPTR ] { if[ dataof[ nextof[p] ] == val ] return p; p = nextof[p]; } return NPTR; } // find element, return the node pointer. pointer find[element val] { pointer p = idata; while[ p != NPTR ] { if[ dataof[p] == val ] return p; p = nextof[p]; } return NPTR; } // pop front element. void pop_front[] { if[ idata != NPTR ] { //Move the first node of the data list to the free list #if 0 pointer p = idata; idata = nextof[idata]; // idata = nextof[idata]; nextof[p] = ifree; // SLList[p].next = ifree; ifree = p; #else pointer p = idata; idata = nextof[idata]; _free[p]; #endif } } // pop back element. void pop_back[] { if[ idata == NPTR ] return; if[ nextof[idata] == NPTR ] { // only 1 node. nextof[idata] = ifree; ifree = idata; idata = NPTR; } else { //Find the last node, p, and its precursor, q. // TODO: find the last node p, and it's perv node q. pointer p = idata, q; while[ nextof[p] != NPTR ] { q = p; p = nextof[ p ]; } // remove *p to free list, update nextof[q] to NPTR. nextof[p] = ifree; ifree = p; nextof[q] = NPTR; } } void show[] { pointer p = idata; for[ ; p != NPTR; p = nextof[p] ] { printf[" %3d ", dataof[p] ]; } printf["n"]; } #define INFOSHOW void info[] { #ifdef INFOSHOW int i; DEBUGVAL[ifree]; DEBUGVAL[idata]; puts["====================n" "indextdatatnextn" "--------------------"]; for[i=0; i