題目
刪除第k個元素。實現一個類並支持表1.3.13中的API:
public class GeneralizedQueue<Item> | |
---|---|
GeneralizedQueue() | 創建一條空隊列 |
boolean isEmpty() | 隊列是否爲空 |
void insert(Item x) | 添加一個元素 |
Item delete(int k) | 刪除並返回最早插入的第k個元素 |
首先用數組實現該數據類型,然後用鏈表實現該數據類型。注意:我們在第3章中介紹的算法和數據結構可以保證insert()和delete()的實現所需的運行時間和隊列中的元素數量成對數關係——請見聯繫3.5.27。
思路
數組實現時,把需要delete的元素的後面所有元素前移一位;鏈表實現時,定位到需要delete的結點的前一個結點。
代碼
數組實現
package Chap1.$3;
//數組實現
public class E38$1<Item>
{
private class Node
{
Node next;
Item item;
}
private Node first;
private Node last;
private int N = 0;
private Item[] a = (Item[]) new Object[1];
public boolean isEmpty()
{
return N == 0;
}
public void resize(int max)
{
Item[] temp = (Item[]) new Object[max];
for (int i = 0; i < N; i++)
temp[i] = a[i];
a = temp;
}
public void insert(Item x)
{
if (N == a.length) resize(2 * a.length);
a[N++] = x;
}
public Item delete(int k)
{
Item item = null;
if (k > N || k < 0) System.out.print("Wrong Input");
else
{
item = a[k - 1];
for (int i = k; i < a.length ; i++)
a[i-1]=a[i];
}
N--;
if (N == a.length/4) resize(a.length / 2);
return item;
}
public static void main(String[] args)
{
E38$1 e = new E38$1();
for (int i = 1; i <= 8; i++)
e.insert(i);
e.delete(3);
e.delete(3);
while(!e.isEmpty())
System.out.print(e.delete(1)+" ");
}
}
鏈表實現
package Chap1.$3;
public class E38$2<Item>
{
private class Node
{
Node next;
Item item;
}
private Node first;
private Node last;
private int N;
public boolean isEmpty()
{
return N == 0;
}
public void insert(Item item)
{
Node oldlast = last;
last = new Node();
last.item = item;
if (isEmpty()) first = last;
else oldlast.next = last;
N++;
}
public Item delete(int k)
{
if (k > N)
{
System.out.print("Wrong Input");
return null;
}
if (k == 1)
{
Item item = first.item;
first = first.next;
return item;
}
else
{
Node current = first;
for (int i = 0; i < k - 2; i++)
{
current = current.next;
}
Item item = current.next.item;
current.next = current.next.next;
return item;
}
}
public void print()
{
for (Node current = first; current != null; current = current.next)
System.out.print(current.item + " ");
}
public static void main(String[] args)
{
E38$2 e = new E38$2();
for (int i = 1; i <= 8; i++)
e.insert(i);
e.delete(1);
e.delete(2);
e.print();
}
}