लिंक्डलिस्ट को लागू करने के लिए जावा प्रोग्राम

इस उदाहरण में, हम जावा में लिंक किए गए सूची डेटा संरचना को लागू करना सीखेंगे।

इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावा प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:

  • जावा लिंक्डलिस्ट
  • जावा जेनरिक

उदाहरण 1: लिंक्डलिस्ट को लागू करने के लिए जावा प्रोग्राम

 class LinkedList ( // create an object of Node class // represent the head of the linked list Node head; // static inner class static class Node ( int value; // connect each node to next node Node next; Node(int d) ( value = d; next = null; ) ) public static void main(String() args) ( // create an object of LinkedList LinkedList linkedList = new LinkedList(); // assign values to each linked list node linkedList.head = new Node(1); Node second = new Node(2); Node third = new Node(3); // connect each node of linked list to next node linkedList.head.next = second; second.next = third; // printing node-value System.out.print("LinkedList: "); while (linkedList.head != null) ( System.out.print(linkedList.head.value + " "); linkedList.head = linkedList.head.next; ) ) )

आउटपुट

 लिंक्डलिस्ट: 1 2 3 

उपरोक्त उदाहरण में, हमने जावा में एकल लिंक की गई सूची को लागू किया है। यहां, लिंक की गई सूची में 3 नोड हैं।

प्रत्येक नोड में मान और अगला होता है। मान चर नोड के मान का प्रतिनिधित्व करता है और अगला अगले नोड के लिंक का प्रतिनिधित्व करता है।

लिंक्डलिस्ट के काम के बारे में जानने के लिए, लिंक्डलिस्ट डेटा संरचना पर जाएं।

उदाहरण 2: लिंक्डलिस्ट का उपयोग करके लिंक्डलिस्ट का कार्यान्वयन करें

जावा एक निर्मित LinkedListवर्ग प्रदान करता है जिसका उपयोग लिंक की गई सूची को लागू करने के लिए किया जा सकता है।

 import java.util.LinkedList; class Main ( public static void main(String() args)( // create a linked list using the LinkedList class LinkedList animals = new LinkedList(); // Add elements to LinkedList animals.add("Dog"); // add element at the beginning of linked list animals.addFirst("Cat"); // add element at the end of linked list animals.addLast("Horse"); System.out.println("LinkedList: " + animals); // access first element System.out.println("First Element: " + animals.getFirst()); // access last element System.out.println("Last Element: " + animals.getLast()); ) )

आउटपुट

 लिंक्डलिस्ट: (बिल्ली, कुत्ता, घोड़ा) पहला तत्व: बिल्ली अंतिम तत्व: घोड़ा

उपरोक्त उदाहरण में, हमने LinkedListजावा में लिंक की गई सूची को लागू करने के लिए कक्षा का उपयोग किया है । यहां, हमने क्लास द्वारा प्रदान की गई विधियों का उपयोग किया है ताकि लिंक की गई सूची से तत्वों और एक्सेस तत्वों को जोड़ा जा सके।

ध्यान दें, हमने लिंक की गई सूची बनाते समय कोण कोष्ठक () का उपयोग किया है। यह दर्शाता है कि लिंक की गई सूची सामान्य प्रकार की है।

दिलचस्प लेख...