-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedList.java
More file actions
70 lines (64 loc) · 1.99 KB
/
linkedList.java
File metadata and controls
70 lines (64 loc) · 1.99 KB
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
68
69
70
import java.util.*;
/* This program in java is to implement linked list. Linked list is a data structure where eac element is considered as an object. Its just like an array of elements but the memory allocated is not continuous. One head should be there which should link to another node. */
/*Creating a class node with 2 datas and a consructor. The data members are the node next and the data that should be added. The constructor is to initialize the data and the node value. */
class node{
node next;
int data;
public node(int data){
this.data=data;
this.next=null;
}
}
/*Another pubic class which has a node head as data member, one constructor to intialize the value, 2 functions to add the elements to the end of the list and to print the added datas and a main function. */
public class linkedList{
node head;
public linkedList(){
this.head=null;
}
public void addNode(int data){
node newhead=new node(data);
if(this.head==null)
head=newhead;
else{
node temp;
for(temp=this.head;temp.next!=null;temp=temp.next);
temp.next=newhead;
}
}
/*Deleting the element in the passed position*/
void deleteNode(int pos){
if(head == null){
return ;
}
node temp = head;
if(pos == 0){
head = temp.next;
}
for(int i = 0;temp != null && i < pos-i-1;i++){
temp=temp.next;
}
if(temp == null || temp.next == null)
return ;
node next=temp.next.next;
temp.next = next;
}
public void print(){
for(node newtemp=this.head;newtemp!=null;newtemp=newtemp.next){
System.out.println(newtemp.data);
}
}
public static void main(String[] args){
linkedList list = new linkedList();
list.addNode(1);
list.addNode(2);
list.addNode(3);
System.out.println("The elements of linked list are:");
list.print();
Scanner Sc = new Scanner(System.in);
System.out.print("Enter the position to be deleted:");
int pos=Sc.nextInt();
list.deleteNode(pos);
System.out.println("The elements of linked list after deletion of element in mentioned position are:");
list.print();
}
}