简单模拟一个双向链表,用java实现

 1 package com.gsh.test05;
 2 
 3 /**
 4  * 节点类
 5  * @param <E>
 6  */
 7 public class Node<E> {
 8     private Node<E> pre;
 9     private E element;
10     private Node<E> next;
11 
12     public Node<E> getPre() {
13         return pre;
14     }
15 
16     public void setPre(Node<E> pre) {
17         this.pre = pre;
18     }
19 
20     public E getElement() {
21         return element;
22     }
23 
24     public void setElement(E e) {
25         this.element = e;
26     }
27 
28     public Node<E> getNext() {
29         return this.next;
30     }
31 
32     public void setNext(Node<E> next) {
33         this.next = next;
34     }
35 
36     @Override
37     public String toString() {
38         return "Node{" +
39                 "pre=" + pre +
40                 ", element=" + element +
41                 ", next=" + next +
42                 '}';
43     }
44 
45 }
 1 package com.gsh.test05;
 2 
 3 /**
 4  * 构建一个模拟的双向链表
 5  * @param <E>
 6  */
 7 
 8 public class MyLinkedList<E> {
 9     private Node<E> headNode;
10     private Node<E> tailNode;
11     private int count = 0;
12 
13     public MyLinkedList() {
14     }
15 
16     public void add(E e) {
17         //将添加的元素封装位一个对象
18         Node<E> n = new Node<>();
19         n.setElement(e);
20 
21         if (headNode == null) {//如果是第一个节点
22             n.setPre(null);
23             //将当前头节点指向该节点
24             headNode = n;
25         } else {//非第一个节点
26             n.setPre(tailNode);
27             n.getPre().setNext(n);
28         }
29 
30         n.setNext(null);
31         //将当尾头节点指当前该节点
32         tailNode = n;
33         count++;
34     }
35 
36     public int getSize(){
37         return this.count;
38     }
39 
40     public E getElement(int index){
41         if(index<0||index>=count){
42             throw new IndexOutOfBoundsException();
43         }
44         Node<E> n = headNode;
45         for (int i = 0; i < index; i++) {
46             n=n.getNext();
47         }
48         return n.getElement();
49     }
50     public static void main(String[] args) {
51         MyLinkedList<String> intList = new MyLinkedList<>();
52         intList.add("aa");
53         intList.add("bb");
54         intList.add("cc");
55         intList.add("dd");
56         intList.add("ee");
57         intList.add("ff");
58         String s = intList.getElement(6);
59         System.out.println(s);
60     }
61 }

 

posted @ 2022-09-22 15:39  青山不语  阅读(27)  评论(0)    收藏  举报