package dataStructures; public class linkedlist { Node head; class Node{ int data; Node next; Node(int data) { this.data = data; this.next =null; } } public void addFirst(int data) { Node newnode = new Node(data); if(head == null) { head = newnode; return; } else { newnode.next = head; head = newnode; return; } } public void addLast(int data) { Node newnode = new Node(data); if(head == null) { head = newnode; return; } Node currnode = head; while(currnode != null) { currnode = currnode.next; } try { currnode.next = newnode; } catch(Exception e1){ System.out.println("Exception occured in addLast method"); } } public void printLlist() { if(head == null) { System.out.println("list is empty"); } Node currnode = head; while(currnode != null) { System.out.print(currnode.data + " "); currnode = currnode.next; } } public static void main(String[] args) { linkedlist list = new linkedlist(); list.addFirst(2); list.addFirst(6); list.addFirst(7); list.addLast(5); list.printLlist(); } }
Quote:while(currnode != null) { currnode = currnode.next; } try { currnode.next = newnode; // here currnode is null }
while(currnode.next != null) { currnode = currnode.next; } try { currnode.next = newnode; }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)