Skip to content

Commit

Permalink
Create LinkedList
Browse files Browse the repository at this point in the history
append,print,reverse,last five elements
  • Loading branch information
Tajmaha8849 committed Feb 19, 2024
1 parent 9c04f15 commit 837f991
Showing 1 changed file with 93 additions and 0 deletions.
93 changes: 93 additions & 0 deletions LinkedList
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import java.util.*;
class Node {
int data;
Node next;

Node(int data)
{
this.data = data;
next = null;
}
}

class LinkedList {
Node head;
// Appends a new node at the end of the list
void append(int new_data){

Node new_node = new Node(new_data);

if (head == null) {
head = new_node;
return;
}
Node last = head;
while (last.next != null) {
last = last.next;
}

last.next = new_node;
}

// Prints the contents of the linked list
void printList(){

Node node = head;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
void reverse(){

Node prev = null;
Node current = head;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;

}
void Lastfive(){
Node temp=head;
int count=0;
while(temp!=null){
System.out.print(" "+temp.data);
temp=temp.next;
count+=1;
if(count==5){
break;
}

}
}
}

public class Main {
public static void main(String[] args)
{
LinkedList obj= new LinkedList();
Scanner sc=new Scanner(System.in);
int n,data;
System.out.print("Enter the size of LL:");
n=sc.nextInt();
for(int i=0;i<n;i++){
System.out.print("Enter"+(i+1)+" element:");
data=sc.nextInt();
obj.append(data);
}

System.out.print("\nLinked list is: ");
obj.printList();
obj.reverse();
System.out.println("\nAfter reversing:");
obj.printList();
System.out.println("\nLast Five elements are:");
obj.Lastfive();

}
}

0 comments on commit 837f991

Please sign in to comment.