Professional Documents
Culture Documents
Lecture-14
Agenda
• Stacks
• Queues
• Linked Lists
Data Structure
• A data structure may be designed to store
data for the purpose of working on it.
• Data Structures for Programming
languages :
– Arrays
– Linked Lists
– Stacks
– Queues …
Linked Lists
• Linked list is a data structure which can be
defined as follows: a linked list is either
empty (null) or a reference to a node
having a reference to a linked list.
• A linked list consists of a chain of objects
o same type, linked together by
pointers/references from one object to
another.
Concepts (Linked List)
Node
Concepts (Linked List) contd..
• Node is an abstract entity that might hold
any kind of data + reference for building
linked lists.
• Representation of a node:
class Node { A node
String data; data
Next: Reference
Node next; To Next node/null
}
Building Linked List
• Create an object of type Node by invoking a no-
argument constructor.
Node firstNode = new Node();
This creates a Node object whose instance
variables are both initialized to value ‘null’.
• Lets put some data into our first node.
firstNode.data = “item1”;
• Similarily to create 2 nodes, we could say
Node secondNode = new Node();
Node thirdNode = new Node();
• To insert data into second and third
nodes, we say
secondNode.data = “item2”;
thirdNode.data = “item3”;
• How about the ‘next’ instance variable of
class Node?
– We set the next fields to build the linked list.
firstNode.next = secondNode;
secondNode.next = thirdNode;
thirdNode.next = null;
Operations on Linked Lists
• Insert: To insert a node into a linked list,
easiest place is at the beginning of list.
NewNode
Ex: New node to be added!
NewItem
item3
item1 item2
l
null
FirstNode
SecondNode ThirdNode
Node NewNode = firstNode;
Create a new node for the beginning
firstNode = new Node();
firstNode.data = “item0”;
firstNode.next = NewNode;
class node
LinkedList.java
{
node next;
String data;
} // My class node is created
public class Main {
// creating 3 nodes
third.data = "item3";
third.next = null;