Topic: Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.
EXAMPLE Input: the node c from the linked list a->b->c->d->d->e
Output: nothing is returned, but the new linked list looks like a->b->d->e
// 关键:考虑要删的节点是head, in the middle, last, empty list.
(1)(2)头和中间节点适用,(3)尾节点:将数据设为某特殊字符,打印时不打印它,(4)空/只有它:直接返回。
// 方法:由于找不到此节点的上一个节点,所以把下一个节点的数据给要删的,下一个的next给这一个的next.实际删了下一个节点,但保留了下一个节点的数据,覆盖了这个节点的数据。(Cannot access the head of the linked list, copy the data from next node over to the current node, delete the next node)
public class List {
int data;
List next;
public List(int d) {
this.data = d;
this.next = null;
}
void appendToTail(int d) {//依次在最后一个节点的后面追加元素
List end = new List(d);
List n = this;
while (n.next != null) {//判断是否是最后一个节点,如果不是,往后移
n = n.next;
}
n.next = end;//把这个节点设为最后一个节点
}
void print() {
List n = this;
System.out.print("{");
while (n != null) {
if (n.next != null)
System.out.print(n.data + ", ");
else
System.out.println(n.data + "}");
n = n.next;
}
}
public static boolean deleteNode(List n){
if(n==null||n.next==null) return false;
n.data=n.next.data;
n.next=n.next.next;
return true;
}
public static void main(String args[]) {
List list = new List(0);
list.appendToTail(1);
list.appendToTail(5);
list.appendToTail(3);
list.print();
deleteNode(list.next.next);
list.print();
}
}
//结果
{0, 1, 5, 3}
{0, 1, 3}