数据结构之双向链表(java实现)

    技术2023-12-28  96

    public class TwoWayLinkList<T> { private class Node { private T item; private Node pre; private Node next; public Node(T item, Node pre, Node next) { this.item = item; this.pre = pre; this.next = next; } } private Node head; private Node last; private int N; public TwoWayLinkList() { this.head = new Node(null, null, null); this.last = null; N = 0; } //清空链表 public void clear() { head.next = null; last = null; N = 0; } //获取链表长度 public int length() { return N; } //判断链表是否为空 public boolean isEmpty() { return N == 0; } //获取第一个元素 public T getFirst() { if (isEmpty()) { return null; } return head.next.item; } //获取最后一个元素 public T getLast() { if (isEmpty()) { return null; } return last.item; } //插入元素t public void insert(T t) { if (isEmpty()) { Node newNode = new Node(t, head, null); head.next = newNode; last = newNode; } else { Node newNode = new Node(t, last, null); last.next = newNode; last = newNode; } N++; } //向指定位置i处插入元素t public void insert(int i,T t){ Node pre=head; for (int j = 0; j < i; j++) { pre=pre.next; } Node curr=pre.next; Node newNode=new Node(t,pre,curr); curr.pre=newNode; pre.next=newNode; N++; } //获取指定位置i处的元素 public T get(int i){ Node n = head.next; for(int index=0;index<i;index++){ n=n.next; } return n.item; } //找到元素t在链表中第一次出现的位置 public int indexOf(T t){ Node n = head; for(int index=0;index<N;index++){ n=n.next; if (n.item.equals(t)){ return index; } } return -1; } //删除位置i处的元素,并返回该元素 public T remove(int i){ Node pre=head; for (int j = 0; j <i ; j++) { pre=pre.next; } Node curr=pre.next; T t=curr.item; Node nextNode=curr.next; pre.next=nextNode; nextNode.pre=pre; N--; return t; } } public class TestTwoWayLinkList { public static void main(String[] args) { TwoWayLinkList <String>linkList=new TwoWayLinkList(); linkList.insert("1"); linkList.insert("2"); linkList.insert(0,"0"); linkList.insert(0,"0.5"); for (int i = 0; i <linkList.length() ; i++) { System.out.println(linkList.get(i)); } System.out.println("___________________________________"); System.out.println("你删除的是:"+ linkList.remove(0)); } }

    欢迎指出不足之处。。。

    Processed: 0.010, SQL: 10