Circular Linked List Traversal Java
- Get link
- X
- Other Apps
PROGRAM TO TRAVERSE A CIRCULAR LINKED LIST
class MAIN{// node static class Node{ int data; Node next;};/* Function to insert a nodeat the beginning of a Circularlinked list */static Node push(Node head_ref, int data){ Node ptr1 = new Node(); Node temp = head_ref; ptr1.data = data; ptr1.next = head_ref; /* If linked list is not null then set the next of last node */ if (head_ref != null) { while (temp.next != head_ref) temp = temp.next; temp.next = ptr1; } else ptr1.next = ptr1; head_ref = ptr1; return head_ref;}/* Function to print nodes in a given Circular linked list */static void printList(Node head){ Node temp = head; if (head != null) { do { System.out.print(temp.data + " "); temp = temp.next; } while (temp != head); }}// Driver Codepublic static void main(String args[]){ /* Initialize lists as empty */ Node head = null; /* Created linked list will be 11.2.56.12 */ head = push(head, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); System.out.println("Contents of Circular " + "Linked List:"); printList(head);}}OUTPUT:
Contents of Circular Linked List 11 2 56 12
- Get link
- X
- Other Apps
Comments
Post a Comment