implement singly linked list in java

In this post, we will see how to implement singly linked list in java.
It is one of the most used data structure. In singly linked list, Node has data and pointer to next node. It does not have pointer to the previous node. Last node ‘s next points to null, so you can iterate over linked list by using this condition.
Node for linked list can be presented as below:

1

2

3

4

5

6

7

8

9

10

classNode{

publicintdata;

publicNode next;

publicvoiddisplayNodeData(){

System.out.println("{ "+data+" } ");

}

}

An example of linked list:

Let’s implement Linked List in java.

Create a java file named SinglyLinkedList.java.

SinglyLinkedList.java

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

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

packageorg.arpit.java2blog;

classNode{

publicintdata;

publicNode next;

publicvoiddisplayNodeData(){

System.out.println("{ "+data+" } ");

}

}

publicclassSinglyLinkedList{

privateNode head;

publicbooleanisEmpty(){

return(head==null);

}

// used to insert a node at the start of linked list

publicvoidinsertFirst(intdata){

Node newNode=newNode();

newNode.data=data;

newNode.next=head;

head=newNode;

}

// used to delete node from start of linked list

publicNode deleteFirst(){

Node temp=head;

head=head.next;

returntemp;

}

// Use to delete node after particular node

publicvoiddeleteAfter(Node after){

Node temp=head;

while(temp.next!=null&&temp.data!=after.data){

temp=temp.next;

}

if(temp.next!=null)

temp.next=temp.next.next;

}

// used to insert a node at the start of linked list

publicvoidinsertLast(intdata){

Node current=head;

while(current.next!=null){

current=current.next;// we'll loop until current.next is null

}

Node newNode=newNode();

newNode.data=data;

current.next=newNode;

}

// For printing Linked List

publicvoidprintLinkedList(){

System.out.println("Printing LinkedList (head --> last) ");

Node current=head;

while(current!=null){

current.displayNodeData();

current=current.next;

}

System.out.println();

}

}

Lets create Main class named LinkedListMain.java to create LinkedList.