-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
1 changed file
with
93 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
|
||
} | ||
} |