鏈表List

來源:互聯網
上載者:User

標籤:

 

 

 

當要建立一個鏈表的時候,首先要建立一個節點類,在Java裡面叫條目(entry表示),這個類是一個嵌套類,裡麵包含三個要素,element, next, previous。

public class Link<E> {

private static class Entry<E> {
private E element;

private Entry<E> next;

private Entry<E> previous;


public Entry(E e, Entry<E> next , Entry<E> previous) {
this.element = e;
this.next = next;
this.previous = previous;
}
}
}

建立一個頭結點和初始頭結點,另外增加一個size用來統計節點數

public class Link<E> {

private transient Entry<E> header = new Entry<E>(null, null, null);
private transient int size = 0;

/**
* Constructs an empty list.
*/
public Link() {
header.next = header.previous = header;
}

private static class Entry<E> {
private E element;

private Entry<E> next;

private Entry<E> previous;


public Entry(E e, Entry<E> next , Entry<E> previous) {
this.element = e;
this.next = next;
this.previous = previous;
}
}
}

添加和擷取、刪除節點

package com.hyd.link;

import java.util.NoSuchElementException;

public class Link<E> {

private transient Entry<E> header = new Entry<E>(null, null, null);
private transient int size = 0;

/**
* Constructs an empty list.
*/
public Link() {
header.next = header.previous = header;
}

public int size() {
return this.size;
}

public boolean add(E e) {
addBefore(e, header);
return true;
}

public E get(int index) {
return entry(index).element;
}

public E remove(int index) {
return remove(entry(index));
}

private Entry<E> addBefore(E e, Entry<E> entry) {
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size ++;
return newEntry;
}

/**
* Returns the indexed entry.
*/
private Entry<E> entry(int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Index: " + index +
", Size: " + size);
}

Entry<E> e = header;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}


return e;
}

private E remove(Entry<E> e) {
if (e == header)
throw new NoSuchElementException();

E result = e.element;
e.previous.next = e.next;
e.next.previous = e.previous;
e.next = e.previous = null;
e.element = null;
size--;
return result;
}

private static class Entry<E> {
private E element;

private Entry<E> next;

private Entry<E> previous;


public Entry(E e, Entry<E> next , Entry<E> previous) {
this.element = e;
this.next = next;
this.previous = previous;
}
}
}

 

 

鏈表List

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.