LinkedList
unknown
java
3 years ago
2.3 kB
1
Indexable
Never
import java.util.Scanner; class Node{ int data; Node next; Node(int data) { this.data=data; } } public class LinkedList { Node start; public void traverse() { if(start==null) { System.out.println("LinkedLis is empty"); return; } Node cursor=start; while(cursor!=null) { System.out.println(cursor.data); cursor=cursor.next; } } public void add() { Scanner scanner=new Scanner(System.in); System.out.print("Enter data: "); int data=Integer.parseInt(scanner.nextLine()); Node node=new Node(data); if(start==null) start=node; else { Node cursor=start; while(cursor.next!=null) cursor=cursor.next; cursor.next=node; } } public int countNodes() { if(start==null) return 0; int count=1; Node cursor=start; while(cursor.next!=null) { cursor=cursor.next; count++; } return count; } public void insert() { Scanner scanner=new Scanner(System.in); System.out.print("Enter position: "); int pos=Integer.parseInt(scanner.nextLine()); System.out.print("Enter data: "); int data=Integer.parseInt(scanner.nextLine()); Node node=new Node(data); if(pos<=1) { node.next=start; start=node; } else { int nodes=countNodes(); if(pos>nodes+1) pos=nodes+1; Node cursor=start; int count=0; while(count<pos-2) { cursor=cursor.next; count++; } node.next=cursor.next; cursor.next=node; } } public void delete(){ Scanner scanner = new Scanner(System.in); System.out.print("Enter Position to Delete: "); int pos = Integer.parseInt(scanner.nextLine()); scanner.close(); if(start == null){ System.out.println("LinkedLis is empty"); return; } Node cursor = start; int curPos = 1; if(pos == 1){ cursor = cursor.next; start = cursor; } else{ while(curPos + 1 != pos){ cursor = cursor.next; curPos++; } cursor.next = cursor.next.next; System.out.println("Node Deleted"); } } public static void main(String[] args) { LinkedList ll=new LinkedList(); Scanner scanner=new Scanner(System.in); System.out.print("Enter number of nodes: "); int nodes=Integer.parseInt(scanner.nextLine()); for(int i=0;i<nodes;i++) ll.add(); ll.traverse(); ll.insert(); ll.traverse(); ll.delete(); ll.traverse(); } }