資料結構與演算法-列表
阿新 • • 發佈:2020-07-28
資料結構與演算法-列表
列表的linkedlist
LinkedList 是通過一個雙向連結串列來實現的,它允許插入所有元素,包括 null,同時,它是執行緒不同步的。雙向連結串列每個結點除了資料域之外,還有一個前指標和後指標,分別指向前驅結點和後繼結點(如果有前驅/後繼的話)。另外,雙向連結串列還有一個 first 指標,指向頭節點,和 last 指標,指向尾節點。
循位置訪問
列表:採用動態儲存的典型結構。
-
每個元素稱為節點( node )。
-
各個節點通過指標或引用彼此聯接,在邏輯上構成一個線性序列。相鄰節點彼此互稱前驅和後繼。如果存在前驅和後繼,那麼必然是唯一的。
-
沒有前驅的節點稱為首,沒有後繼的節點稱為末。此外,可以認為頭存在一個哨兵前驅稱為頭,末存在一個哨兵後繼稱為尾。
-
可以認為 頭、首、末、尾 節點的秩分別為 -1、0、n-1、n。
-
在訪問時儘量不使用循秩訪問,而使用循位置訪問。即利用節點之間的相互引用,找到特定的節點。
列表中元素(原始碼解析)
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable { /** *連結串列的節點個數 */ transient int size = 0; /** * 指向頭節點的指標 */ transient Node<E> first; /** * 指向尾節點的指標 */ transient Node<E> last;
列表構造器
/**
* 空構造器.
*/
public LinkedList() {
}
/**
* 包含集合中元素的構造器
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
public boolean addAll(Collection<? extends E> c) { return addAll(size, c); } public boolean addAll(int index, Collection<? extends E> c) { checkPositionIndex(index); Object[] a = c.toArray(); int numNew = a.length; if (numNew == 0) return false; Node<E> pred, succ; if (index == size) { succ = null; pred = last; } else { succ = node(index); pred = succ.prev; } for (Object o : a) { @SuppressWarnings("unchecked") E e = (E) o; Node<E> newNode = new Node<>(pred, e, null); if (pred == null) first = newNode; else pred.next = newNode; pred = newNode; } if (succ == null) { last = pred; } else { pred.next = succ; succ.prev = pred; } size += numNew; modCount++;//操作次數 return true; }
元素的新增
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
/**
* 新增為第一個元素.
*/
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)//如果第一個為空,則原List為空
last = newNode;//list的first和last都設定為加入元素
else
f.prev = newNode;
size++;
modCount++;
}
/**
* 新增為尾元素.
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)//同上
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
/**
* 新增到指定Node之前.
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
元素的刪除
/**
* 去除連結有三種
* 第一種:first連結
*/
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
/**
* 第二種:last連結
*/
private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
final E element = l.item;
final Node<E> prev = l.prev;
l.item = null;
l.prev = null; // help GC
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
/**
* 第三種:中間連結.
*/
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
常用的方法
/**一些常用的方法
* Returns the first element in this list.
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
/**
* Returns the last element in this list.
*/
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
/**
* Removes and returns the first element from this list.
*/
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* Removes and returns the last element from this list.
*/
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
* Inserts the specified element at the beginning of this list.
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* Appends the specified element to the end of this list.
*/
public void addLast(E e) {
linkLast(e);
}
/**
* 判斷是否包含某一元素
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* Returns the number of elements in this list.
*/
public int size() {
return size;
}
/**
* Appends the specified element to the end of this list.
*/
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If this list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* {@code i} such that
*/
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
/**
* Removes all of the elements from this list.
* The list will be empty after this call returns.
*/
public void clear() {
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
// Positional Access Operations
/**
* Returns the element at the specified position in this list.
*/
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
/**
* Replaces the element at the specified position in this list with the
* specified element.
*/
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
/**
* Inserts the specified element at the specified position in this list.
* Shifts the element currently at that position (if any) and any
* subsequent elements to the right (adds one to their indices).
*/
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/**
* Removes the element at the specified position in this list. Shifts any
* subsequent elements to the left (subtracts one from their indices).
* Returns the element that was removed from the list.
*/
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Returns the (non-null) Node at the specified element index.
*/
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
// Search Operations
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}
迭代器
/**
* 迭代器有兩種:
* ListIterator
*/
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException();
lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
Node<E> lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size) {
action.accept(next.item);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
/**
* 第二種:descendingIterator對ListItr的應用
*/
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
/**
* Adapter to provide descending iterators via ListItr.previous
*/
private class DescendingIterator implements Iterator<E> {
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}
唯一化
無序列表
有序列表
選擇排序
原理
c++方法
效能比較
JAVA方法(不是關於LinkedList的)
public class ChooseSort {
static int[] array = {3,2,4,1,5,0};
public static void chooseSort(int[] a)
{
int max = 0;
int index = 0;
//外層迴圈,控制選擇的次數,陣列長度為6,一共需要選擇5次
for(int i=0;i<a.length-1;i++)
{
for(int j=0;j<a.length-i;j++)
{
if(max < a[j])
{
max = a[j];
index = j;
}
}
//每次選擇完成後,max中存放的是該輪選出的最大值
//將max指向位置的元素和陣列最後一個元素位置互換
int temp = a[a.length-i-1];
a[a.length-i-1] = max;
a[index] = temp;
//清空max和index,便於下次
max=0;
index =0;
System.out.println("經過第"+(i+1)+"輪選擇後,陣列為"+Arrays.toString(a));
}
}
public static void main(String[] args) {
chooseSort(array);
}
}
插入排序
原理
c++方法
template <typename T> //列表的插入排序演算法:對起始於位置p的n個元素排序
void List<T>::insertionSort ( ListNodePosi(T) p, int n ) { //valid(p) && rank(p) + n <= size
for ( int r = 0; r < n; r++ ) { //逐一為各節點
insertA ( search ( p->data, r, p ), p->data ); //查詢適當的位置並插入
p = p->succ;
remove ( p->pred ); //轉向下一節點
}
}
template <typename T> //在有序列表內節點p(可能是trailer)的n個(真)前驅中,找到不大於e的最後者
ListNodePosi(T) List<T>::search ( T const& e, int n, ListNodePosi(T) p ) const {
// assert: 0 <= n <= rank(p) < _size
do {
p = p->pred; n--; //從右向左
} while ( ( -1 < n ) && ( e < p->data ) ); //逐個比較,直至命中或越界
return p; //返回查詢終止的位置
} //失敗時,返回區間左邊界的前驅(可能是header)——呼叫者可通過valid()判斷成功與否
逆序對
JAVA方法
public class LinkedInsertSort {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public static ListNode insertionSortList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode pre = head;//pre指向已經有序的節點
ListNode cur = head.next;//cur指向待排序的節點
ListNode aux = new ListNode(-1);//輔助節點
aux.next = head;
while(cur!=null){
if(cur.val<pre.val){
//先把cur節點從當前連結串列中刪除,然後再把cur節點插入到合適位置
pre.next = cur.next;
//從前往後找到l2.val>cur.val,然後把cur節點插入到l1和l2之間
ListNode l1 = aux;
ListNode l2 = aux.next;
while(cur.val>l2.val){
l1 = l2;
l2 = l2.next;
}
//把cur節點插入到l1和l2之間
l1.next = cur;
cur.next = l2;//插入合適位置
cur = pre.next;//指向下一個待處理節點
}else{
pre = cur;
cur = cur.next;
}
}
return aux.next;
}
}