代码之家  ›  专栏  ›  技术社区  ›  Snowman

从头创建LinkedList类

  •  34
  • Snowman  · 技术社区  · 15 年前

    我们接到了一个任务,要从头开始创建一个LinkedList,但绝对没有阅读资料来指导我们完成这个偏头痛引发的任务。同时,网上的一切似乎都只是使用Java内置的LinkedList方法和其他东西。无论如何,当使用Java的默认内容时,链表是非常有意义的,但是从头开始创建它毫无意义。假设我有

    public class LinkedList {
      private LinkedList next;  
      private final String word;
      // constructor
      public LinkedList(String word, LinkedList next) {
        this.word = word;
        this.next = next;
      }
    

    因此神奇的是我们有一个链表。怎么回事?如何创建这样的链接列表?这是怎么工作的?我应该编写一个append方法来添加 String word 参数结束于 this 链接列表。我试着查看内置java linkedlist类的addLast内置方法,但这对我没有帮助,因为我真的不明白发生了什么。有谁愿意帮我:)

    11 回复  |  直到 15 年前
        1
  •  43
  •   Laurence Gonsalves    8 年前

    如果你真的在构建一个真正的系统,那么是的,如果你需要的东西在标准库中可用的话,你通常只需要使用标准库中的东西。也就是说,不要认为这是毫无意义的练习。理解事物如何工作是很好的,理解链表是理解更复杂的数据结构的一个重要步骤,其中许多不存在于标准库中。

    创建链表的方式与Java collections API的方式有些不同。Collections API正试图遵循更复杂的接口。Collections API链表也是一个双链表,而您正在构建一个单链表。你所做的事更适合做作业。

    和你的 LinkedList null 当你需要一个空名单的时候。

    想想 next

    这是一张 链表 包含3个元素:

    linked list diagram

    链表 无效的 ). 所以你可以治疗 就像另一个恰好短了一个元素的列表一样。

    无效的 . 这将用于创建一个1元素列表。

    要附加,请检查 是 . 如果是,则创建新的一个元素列表并设置 下一个 为了这个。

    next = new LinkedList(word);
    

    无效的 ,然后附加到 相反。

    next.append(word);
    

    * 并且不会冒堆栈溢出的风险,因为我猜想,对于你的任务来说,不需要复杂程度。


        2
  •  24
  •   Amir Afghani    12 年前

    你所编码的不是 LinkedList ,至少我不认识。对于此作业,您需要创建两个类:

    LinkNode
    LinkedList
    

    一个 LinkNode 对于包含的数据有一个成员字段,并且 参考下一个 链接节点 LinkedList . 是的,它是一个自引用的数据结构。一个 只是有一个特别的 链接节点

    当您在 链表 ,你将遍历所有 LinkNode's 直到你到达最后一个。这个 下一个应为空。然后你就构建了一个新的 链接节点 在这里,设置它的值,并将其添加到 .

    public class LinkNode { 
    
        String data;
        LinkNode next;
    
        public LinkNode(String item) { 
    
           data = item;
    
        }
    
    }
    
    public class LinkedList { 
    
        LinkNode head;
    
        public LinkedList(String item) { 
    
           head = new LinkNode(item);
    
        }
    
        public void add(String item) { 
    
           //pseudo code: while next isn't null, walk the list
           //once you reach the end, create a new LinkNode and add the item to it.  Then
           //set the last LinkNode's next to this new LinkNode
    
        }
    
    
    }
    
        3
  •  11
  •   Evan Plaice    11 年前

    我为我的算法创建了这个类,我将其归类为一个垫脚石,以便在开始为赋值编写双链接队列类之前更好地理解它。

    代码如下:

    import java.util.Iterator;
    import java.util.NoSuchElementException;
    
    public class LinkedList<T> implements Iterable<T> {
        private Node first;
        private Node last;
        private int N;
    
        public LinkedList() {
            first = null;
            last = null;
            N = 0;
        }
    
        public void add(T item) {
            if (item == null) { throw new NullPointerException("The first argument for addLast() is null."); }
            if (!isEmpty()) {
                Node prev = last;
                last = new Node(item, null);
                prev.next = last;
            }
            else {
                last = new Node(item, null);
                first = last;
            }
            N++;
        }
    
        public boolean remove(T item) {
            if (isEmpty()) { throw new IllegalStateException("Cannot remove() from and empty list."); }
            boolean result = false;
            Node prev = first;
            Node curr = first;
            while (curr.next != null || curr == last) {
                if (curr.data.equals(item)) {
                    // remove the last remaining element
                    if (N == 1) { first = null; last = null; }
                    // remove first element
                    else if (curr.equals(first)) { first = first.next; }
                    // remove last element
                    else if (curr.equals(last)) { last = prev; last.next = null; }
                    // remove element
                    else { prev.next = curr.next; }
                    N--;
                    result = true;
                    break;
                }
                prev = curr;
                curr = prev.next;
            }
            return result;
        }
    
        public int size() {
            return N;
        }
    
        public boolean isEmpty() {
            return N == 0;
        }
    
        private class Node {
            private T data;
            private Node next;
    
            public Node(T data, Node next) {
                this.data = data;
                this.next = next;
            }
        }
    
        public Iterator<T> iterator() { return new LinkedListIterator(); }
    
        private class LinkedListIterator implements Iterator<T> {
            private Node current = first;
    
            public T next() {
                if (!hasNext()) { throw new NoSuchElementException(); }
                T item = current.data;
                current = current.next;
                return item;
            }
    
            public boolean hasNext() { return current != null; }
    
            public void remove() { throw new UnsupportedOperationException(); }
        }
    
        @Override public String toString() {
            StringBuilder s = new StringBuilder();
            for (T item : this)
                s.append(item + " ");
            return s.toString();
        }
    
        public static void main(String[] args) {
            LinkedList<String> list = new LinkedList<>();
            while(!StdIn.isEmpty()) {
                String input = StdIn.readString();
                if (input.equals("print")) { StdOut.println(list.toString()); continue; }
                if (input.charAt(0) == ('+')) { list.add(input.substring(1)); continue; }
                if (input.charAt(0) == ('-')) { list.remove(input.substring(1)); continue; }
                break;
            }
        }
    }
    

    如果您愿意,还可以考虑实施:

    • addFirst()-将新项添加到LinkedList的开头
    • removeFirst()-从LinkedList中删除第一个项
    • addAll()-将项目列表/数组添加到LinkedList
    • removeAll()-从LinkedList中移除项的列表/数组
    • contains()-检查LinkedList是否包含项

    老实说,只需要几行代码就可以使这个列表成为一个双链接列表。此列表与双链接列表的主要区别在于,双链接列表的节点实例需要指向列表中上一个元素的附加引用。

    与递归实现相比,这样做的好处是速度更快,而且在遍历大型列表时不必担心堆栈被淹没。

    • 用“+”预置一个值将添加到列表中。
    • 用“--”进行前缀将删除列表中的第一个事件。

    如果您从未见过其中一种方法的内部原理,我建议您在调试器中逐步完成以下步骤:

    • remove()-从头到尾遍历列表。如果找到匹配项,它将删除该项并连接链中上一个和下一个链接之间的断开链接。当没有上一个或下一个链接时,将添加特殊异常。
    • toString()-使用foreach迭代器简单地从头到尾遍历列表链。

    虽然对于数组列表这样的列表有更好、更有效的方法,但是理解应用程序如何通过引用/指针进行遍历对于理解有多少更高级别的数据结构工作是不可或缺的。

        4
  •  8
  •   Stephen C    10 年前

    提示1:阅读链接列表的说明 http://en.wikipedia.org/wiki/Linked_list

    提示2:LinkedList的Java实现是一个双链表。你的是一个单链表。这些算法并不直接适用。


    也:

    ... 但是从头开始创建(一个链表类)毫无意义。

    真实的 学习

    因此神奇的是我们有一个链表

    实际上有一个开放的数据类型,可以用来构建(某种)列表。但这不是你老师想要的。当然也不会被认为是 有用的 列表抽象。一个有用的抽象包括:

    • 阻止程序员“破坏”列表的抽象层;例如,通过意外地创建一个循环,或意外地在两个列表中缝合一个子列表来创建倒排树。

        5
  •  5
  •   OmnipotentEntity    15 年前

    当然,一个链表对于编程n00bs来说有点混乱,很有诱惑力的是把它看作俄罗斯玩偶,因为它看起来就是这样,一个Linked List对象中的LinkedList对象。但这是一种很难想象的感觉,相反,把它当作一台电脑来看待。

    LinkedList=Data+下一个成员

    因此,一个由5名成员组成的LinkedList将是:

    但你可以简单地认为:

    数据1->数据2->数据3->数据4->数据5->空

    public void append(LinkedList myNextNode) {
      LinkedList current = this; //Make a variable to store a pointer to this LinkedList
      while (current.next != NULL) { //While we're not at the last node of the LinkedList
        current = current.next; //Go further down the rabbit hole.
      }
      current.next = myNextNode; //Now we're at the end, so simply replace the NULL with another Linked List!
      return; //and we're done!
    }
    

    当然,这是非常简单的代码 无限循环如果你给它一个循环链表!但这是最基本的。

        6
  •  4
  •   Shiv Buyya    10 年前

    import java.io.DataInputStream;
    import java.io.IOException;
    
    
    public class LinkedListTest {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub      
        Node root = null;
    
        DataInputStream reader = new DataInputStream(System.in);        
        int op = 0;
        while(op != 6){
    
            try {
                System.out.println("Enter Option:\n1:Insert Front 2:Delete Front 3:Insert Rear 4:Delete Rear 5:Display List 6:Exit");
                //op = reader.nextInt();
                op = Integer.parseInt(reader.readLine());
                switch (op) {
                case 1:
                    System.out.println("Enter Value: ");
                    int val = Integer.parseInt(reader.readLine());
                    root = insertNodeFront(val,root);
                    display(root);
                    break;
                case 2:
                    root=removeNodeFront(root);
                    display(root);
                    break;
                case 3:
                    System.out.println("Enter Value: ");
                    val = Integer.parseInt(reader.readLine());
                    root = insertNodeRear(val,root);
                    display(root);
                    break;
                case 4:
                    root=removeNodeRear(root);
                    display(root);
                    break;
                case 5:
                    display(root);
                    break;
                default:
                    System.out.println("Invalid Option");
                    break;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("Exited!!!");
        try {
            reader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }
    
    static Node insertNodeFront(int value, Node root){  
        Node temp = new Node(value);
        if(root==null){
            return temp; // as root or first
        }
        else
        {
            temp.next = root;
            return temp;
        }               
    }
    
    static Node removeNodeFront(Node root){
        if(root==null){
            System.out.println("List is Empty");
            return null;
        }
        if(root.next==null){
            return null; // remove root itself
        }
        else
        {
            root=root.next;// make next node as root
            return root;
        }               
    }
    
    static Node insertNodeRear(int value, Node root){   
        Node temp = new Node(value);
        Node cur = root;
        if(root==null){
            return temp; // as root or first
        }
        else
        {
            while(cur.next!=null)
            {
                cur = cur.next;
            }
            cur.next = temp;
            return root;
        }               
    }
    
    static Node removeNodeRear(Node root){
        if(root==null){
            System.out.println("List is Empty");
            return null;
        }
        Node cur = root;
        Node prev = null;
        if(root.next==null){
            return null; // remove root itself
        }
        else
        {
            while(cur.next!=null)
            {
                prev = cur;
                cur = cur.next;
            }
            prev.next=null;// remove last node
            return root;
        }               
    }
    
    static void display(Node root){
        System.out.println("Current List:");
        if(root==null){
            System.out.println("List is Empty");
            return;
        }
        while (root!=null){
            System.out.print(root.val+"->");
            root=root.next;
        }
        System.out.println();
    }
    
    static class Node{
        int val;
        Node next;
        public Node(int value) {
            // TODO Auto-generated constructor stub
            val = value;
            next = null;
        }
    }
    }
    
        7
  •  4
  •   Vpn_talent    9 年前

    具有以下功能的链表程序

    1 Insert At Start
    2 Insert At End
    3 Insert At any Position
    4 Delete At any Position
    5 Display 
    6 Get Size
    7 Empty Status
    8 Replace data at given postion
    9 Search Element by position
    10 Delete a Node by Given Data
    11 Search Element Iteratively
    12 Search Element Recursively
    
    
    
    
     package com.elegant.ds.linkedlist.practice;
    
    import java.util.Scanner;
    
    class Node {
    
        Node link = null;
        int data = 0;
    
        public Node() {
            link = null;
            data = 0;
        }
    
        public Node(int data, Node link) {
            this.data = data;
            this.link = null;
        }
    
        public Node getLink() {
            return link;
        }
    
        public void setLink(Node link) {
            this.link = link;
        }
    
        public int getData() {
            return data;
        }
    
        public void setData(int data) {
            this.data = data;
        }
    
    }
    
    class SinglyLinkedListImpl {
    
        Node start = null;
        Node end = null;
        int size = 0;
    
        public SinglyLinkedListImpl() {
            start = null;
            end = null;
            size = 0;
        }
    
        public void insertAtStart(int data) {
            Node nptr = new Node(data, null);
            if (start == null) {
                start = nptr;
                end = start;
            } else {
                nptr.setLink(start);
                start = nptr;
            }
            size++;
        }
    
        public void insertAtEnd(int data) {
            Node nptr = new Node(data, null);
            if (start == null) {
                start = nptr;
                end = nptr;
            } else {
                end.setLink(nptr);
                end = nptr;
            }
            size++;
        }
    
        public void insertAtPosition(int position, int data) {
            Node nptr = new Node(data, null);
            Node ptr = start;
            position = position - 1;
            for (int i = 1; i < size; i++) {
                if (i == position) {
                    Node temp = ptr.getLink();
                    ptr.setLink(nptr);
                    nptr.setLink(temp);
                    break;
                }
                ptr = ptr.getLink();
            }
            size++;
        }
    
        public void repleaceDataAtPosition(int position, int data) {
            if (start == null) {
                System.out.println("Empty!");
                return;
            }
    
            Node ptr = start;
            for (int i = 1; i < size; i++) {
                if (i == position) {
                    ptr.setData(data);
                }
                ptr = ptr.getLink();
            }
        }
    
        public void deleteAtPosition(int position) {
            if (start == null) {
                System.out.println("Empty!");
                return;
            }
    
            if (position == size) {
                Node startPtr = start;
                Node endPtr = start;
                while (startPtr != null) {
                    endPtr = startPtr;
                    startPtr = startPtr.getLink();
                }
                end = endPtr;
                end.setLink(null);
                size--;
                return;
            }
    
            Node ptr = start;
            position = position - 1;
            for (int i = 1; i < size; i++) {
    
                if (i == position) {
                    Node temp = ptr.getLink();
                    temp = temp.getLink();
                    ptr.setLink(temp);
                    break;
                }
                ptr = ptr.getLink();
            }
            size--;
        }
    
        public void deleteNodeByGivenData(int data) {
            if (start == null) {
                System.out.println("Empty!");
                return;
            }
    
            if (start.getData() == data && start.getLink() == null) {
                start = null;
                end = null;
                size--;
                return;
            }
    
            if (start.getData() == data && start.getLink() != null) {
                start = start.getLink();
                size--;
                return;
            }
    
            if (end.getData() == data) {
                Node startPtr = start;
                Node endPtr = start;
    
                startPtr = startPtr.getLink();
                while (startPtr.getLink() != null) {
                    endPtr = startPtr;
                    startPtr = startPtr.getLink();
                }
                end = endPtr;
                end.setLink(null);
                size--;
                return;
            }
    
            Node startPtr = start;
            Node prevLink = startPtr;
            startPtr = startPtr.getLink();
            while (startPtr.getData() != data && startPtr.getLink() != null) {
                prevLink = startPtr;
                startPtr = startPtr.getLink();
            }
            if (startPtr.getData() == data) {
                Node temp = prevLink.getLink();
                temp = temp.getLink();
                prevLink.setLink(temp);
                size--;
                return;
            }
    
            System.out.println(data + " not found!");
        }
    
        public void disply() {
            if (start == null) {
                System.out.println("Empty!");
                return;
            }
    
            if (start.getLink() == null) {
                System.out.println(start.getData());
                return;
            }
    
            Node ptr = start;
            System.out.print(ptr.getData() + "->");
            ptr = start.getLink();
            while (ptr.getLink() != null) {
                System.out.print(ptr.getData() + "->");
                ptr = ptr.getLink();
            }
            System.out.println(ptr.getData() + "\n");
        }
    
        public void searchElementByPosition(int position) {
            if (position == 1) {
                System.out.println("Element at " + position + " is : " + start.getData());
                return;
            }
    
            if (position == size) {
                System.out.println("Element at " + position + " is : " + end.getData());
                return;
            }
    
            Node ptr = start;
            for (int i = 1; i < size; i++) {
                if (i == position) {
                    System.out.println("Element at " + position + " is : " + ptr.getData());
                    break;
                }
                ptr = ptr.getLink();
            }
        }
    
        public void searchElementIteratively(int data) {
    
            if (isEmpty()) {
                System.out.println("Empty!");
                return;
            }
    
            if (start.getData() == data) {
                System.out.println(data + " found at " + 1 + " position");
                return;
            }
    
            if (start.getLink() != null && end.getData() == data) {
                System.out.println(data + " found at " + size + " position");
                return;
            }
    
            Node startPtr = start;
            int position = 0;
            while (startPtr.getLink() != null) {
                ++position;
                if (startPtr.getData() == data) {
                    break;
                }
                startPtr = startPtr.getLink();
            }
            if (startPtr.getData() == data) {
                System.out.println(data + " found at " + position);
                return;
            }
    
            System.out.println(data + " No found!");
        }
    
        public void searchElementRecursively(Node start, int data, int count) {
    
            if (isEmpty()) {
                System.out.println("Empty!");
                return;
            }
            if (start.getData() == data) {
                System.out.println(data + " found at " + (++count));
                return;
            }
            if (start.getLink() == null) {
                System.out.println(data + " not found!");
                return;
            }
            searchElementRecursively(start.getLink(), data, ++count);
        }
    
        public int getSize() {
            return size;
        }
    
        public boolean isEmpty() {
            return start == null;
        }
    }
    
    public class SinglyLinkedList {
    
        @SuppressWarnings("resource")
        public static void main(String[] args) {
            SinglyLinkedListImpl listImpl = new SinglyLinkedListImpl();
            System.out.println("Singly Linked list : ");
            boolean yes = true;
            do {
                System.out.println("1 Insert At Start :");
                System.out.println("2 Insert At End :");
                System.out.println("3 Insert At any Position :");
                System.out.println("4 Delete At any Position :");
                System.out.println("5 Display :");
                System.out.println("6 Get Size");
                System.out.println("7 Empty Status");
                System.out.println("8 Replace data at given postion");
                System.out.println("9 Search Element by position ");
                System.out.println("10 Delete a Node by Given Data");
                System.out.println("11 Search Element Iteratively");
                System.out.println("12 Search Element Recursively");
                System.out.println("13 Exit :");
                Scanner scanner = new Scanner(System.in);
                int choice = scanner.nextInt();
                switch (choice) {
                case 1:
                    listImpl.insertAtStart(scanner.nextInt());
                    break;
    
                case 2:
                    listImpl.insertAtEnd(scanner.nextInt());
                    break;
    
                case 3:
                    int position = scanner.nextInt();
                    if (position <= 1 || position > listImpl.getSize()) {
                        System.out.println("invalid position!");
                    } else {
                        listImpl.insertAtPosition(position, scanner.nextInt());
                    }
                    break;
    
                case 4:
                    int deletePosition = scanner.nextInt();
                    if (deletePosition <= 1 || deletePosition > listImpl.getSize()) {
                        System.out.println("invalid position!");
                    } else {
                        listImpl.deleteAtPosition(deletePosition);
                    }
                    break;
    
                case 5:
                    listImpl.disply();
                    break;
    
                case 6:
                    System.out.println(listImpl.getSize());
                    break;
    
                case 7:
                    System.out.println(listImpl.isEmpty());
                    break;
    
                case 8:
                    int replacePosition = scanner.nextInt();
                    if (replacePosition < 1 || replacePosition > listImpl.getSize()) {
                        System.out.println("Invalid position!");
                    } else {
                        listImpl.repleaceDataAtPosition(replacePosition, scanner.nextInt());
                    }
                    break;
    
                case 9:
                    int searchPosition = scanner.nextInt();
                    if (searchPosition < 1 || searchPosition > listImpl.getSize()) {
                        System.out.println("Invalid position!");
                    } else {
                        listImpl.searchElementByPosition(searchPosition);
                    }
                    break;
    
                case 10:
                    listImpl.deleteNodeByGivenData(scanner.nextInt());
                    break;
    
                case 11:
                    listImpl.searchElementIteratively(scanner.nextInt());
                    break;
    
                case 12:
                    listImpl.searchElementRecursively(listImpl.start, scanner.nextInt(), 0);
                    break;
    
                default:
                    System.out.println("invalid choice");
                    break;
                }
            } while (yes);
        }
    }
    

    它将帮助你在链接列表。

        8
  •  1
  •   Kevin Stricker    15 年前

    我是如何创建这样一个linkedlist的。这是怎么工作的? 这就是所有的链表。具有指向列表中下一项的链接的项。只要在列表的开头保留对项的引用,就可以使用对下一个值的每个后续引用遍历整个内容。

    this.next.Append(word);
    
        9
  •  0
  •   d.danailov Felix Kling    11 年前

    请阅读本文: How To Implement a LinkedList Class From Scratch In Java

    package com.crunchify.tutorials;
    
    /**
     * @author Crunchify.com
     */
    
    public class CrunchifyLinkedListTest {
    
        public static void main(String[] args) {
            CrunchifyLinkedList lList = new CrunchifyLinkedList();
    
            // add elements to LinkedList
            lList.add("1");
            lList.add("2");
            lList.add("3");
            lList.add("4");
            lList.add("5");
    
            /*
             * Please note that primitive values can not be added into LinkedList
             * directly. They must be converted to their corresponding wrapper
             * class.
             */
    
            System.out.println("lList - print linkedlist: " + lList);
            System.out.println("lList.size() - print linkedlist size: " + lList.size());
            System.out.println("lList.get(3) - get 3rd element: " + lList.get(3));
            System.out.println("lList.remove(2) - remove 2nd element: " + lList.remove(2));
            System.out.println("lList.get(3) - get 3rd element: " + lList.get(3));
            System.out.println("lList.size() - print linkedlist size: " + lList.size());
            System.out.println("lList - print linkedlist: " + lList);
        }
    }
    
    class CrunchifyLinkedList {
        // reference to the head node.
        private Node head;
        private int listCount;
    
        // LinkedList constructor
        public CrunchifyLinkedList() {
            // this is an empty list, so the reference to the head node
            // is set to a new node with no data
            head = new Node(null);
            listCount = 0;
        }
    
        public void add(Object data)
        // appends the specified element to the end of this list.
        {
            Node crunchifyTemp = new Node(data);
            Node crunchifyCurrent = head;
            // starting at the head node, crawl to the end of the list
            while (crunchifyCurrent.getNext() != null) {
                crunchifyCurrent = crunchifyCurrent.getNext();
            }
            // the last node's "next" reference set to our new node
            crunchifyCurrent.setNext(crunchifyTemp);
            listCount++;// increment the number of elements variable
        }
    
        public void add(Object data, int index)
        // inserts the specified element at the specified position in this list
        {
            Node crunchifyTemp = new Node(data);
            Node crunchifyCurrent = head;
            // crawl to the requested index or the last element in the list,
            // whichever comes first
            for (int i = 1; i < index && crunchifyCurrent.getNext() != null; i++) {
                crunchifyCurrent = crunchifyCurrent.getNext();
            }
            // set the new node's next-node reference to this node's next-node
            // reference
            crunchifyTemp.setNext(crunchifyCurrent.getNext());
            // now set this node's next-node reference to the new node
            crunchifyCurrent.setNext(crunchifyTemp);
            listCount++;// increment the number of elements variable
        }
    
        public Object get(int index)
        // returns the element at the specified position in this list.
        {
            // index must be 1 or higher
            if (index <= 0)
                return null;
    
            Node crunchifyCurrent = head.getNext();
            for (int i = 1; i < index; i++) {
                if (crunchifyCurrent.getNext() == null)
                    return null;
    
                crunchifyCurrent = crunchifyCurrent.getNext();
            }
            return crunchifyCurrent.getData();
        }
    
        public boolean remove(int index)
        // removes the element at the specified position in this list.
        {
            // if the index is out of range, exit
            if (index < 1 || index > size())
                return false;
    
            Node crunchifyCurrent = head;
            for (int i = 1; i < index; i++) {
                if (crunchifyCurrent.getNext() == null)
                    return false;
    
                crunchifyCurrent = crunchifyCurrent.getNext();
            }
            crunchifyCurrent.setNext(crunchifyCurrent.getNext().getNext());
            listCount--; // decrement the number of elements variable
            return true;
        }
    
        public int size()
        // returns the number of elements in this list.
        {
            return listCount;
        }
    
        public String toString() {
            Node crunchifyCurrent = head.getNext();
            String output = "";
            while (crunchifyCurrent != null) {
                output += "[" + crunchifyCurrent.getData().toString() + "]";
                crunchifyCurrent = crunchifyCurrent.getNext();
            }
            return output;
        }
    
        private class Node {
            // reference to the next node in the chain,
            // or null if there isn't one.
            Node next;
            // data carried by this node.
            // could be of any type you need.
            Object data;
    
            // Node constructor
            public Node(Object dataValue) {
                next = null;
                data = dataValue;
            }
    
            // another Node constructor if we want to
            // specify the node to point to.
            public Node(Object dataValue, Node nextValue) {
                next = nextValue;
                data = dataValue;
            }
    
            // these methods should be self-explanatory
            public Object getData() {
                return data;
            }
    
            public void setData(Object dataValue) {
                data = dataValue;
            }
    
            public Node getNext() {
                return next;
            }
    
            public void setNext(Node nextValue) {
                next = nextValue;
            }
        }
    }
    

    输出

    lList - print linkedlist: [1][2][3][4][5]
    lList.size() - print linkedlist size: 5
    lList.get(3) - get 3rd element: 3
    lList.remove(2) - remove 2nd element: true
    lList.get(3) - get 3rd element: 4
    lList.size() - print linkedlist size: 4
    lList - print linkedlist: [1][3][4][5]
    
        10
  •  0
  •   MAnoj Sarnaik    8 年前

    class Node {
        int data;
        Node next;
    
        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
    
    public class LinkedListManual {
    
        Node node;
    
        public void pushElement(int next_node) {
            Node nd = new Node(next_node);
            nd.next = node;
            node = nd;
        }
    
        public int getSize() {
            Node temp = node;
            int count = 0;
            while (temp != null) {
                count++;
                temp = temp.next;
            }
            return count;
        }
    
        public void getElement() {
            Node temp = node;
            while (temp != null) {
                System.out.println(temp.data);
                temp = temp.next;
            }
        }
    
        public static void main(String[] args) {
            LinkedListManual obj = new LinkedListManual();
            obj.pushElement(1);
            obj.pushElement(2);
            obj.pushElement(3);
            obj.getElement(); //get element
            System.out.println(obj.getSize());  //get size of link list
        }
    
    }
    
        11
  •  -1
  •   Eadhunath    12 年前
    class Node
    {
      int data;
         Node link;
    
         public Node()
         {
             data=0;
             link=null;
            }
    
         Node ptr,start,temp;
    
        void create()throws  IOException
         {
             int n;
             BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
             System.out.println("Enter first data");
             this.data=Integer.parseInt(br.readLine());
             ptr=this;
             start=ptr;
             char ins ='y';
             do
             {
                 System.out.println("Wanna Insert another node???");
                 ins=(char)br.read();
                 br.read();
                 if(ins=='y')
                 {
                     temp=new Node();
                     System.out.println("Enter next data");
                     temp.data=Integer.parseInt(br.readLine());
                     temp.link=null;
                     ptr.link=temp;
                     temp=null;
                     ptr=ptr.link;
                    }
                }while(ins=='y');
            }
    
    public static void main(String args[])throws IOException
         {
           Node first= new Node();
           first.create();
    }
    }
    
    推荐文章