更新時間:2022-12-30 10:43:21 來源:動力節點 瀏覽1145次
鏈表刪除節點的方法是什么?動力節點小編來告訴大家。
package com.lab2.test2;
public class DeleteNode {
public static void main(String[] args) {
Node node1 = new Node();
node1.data = 1;
Node node2 = new Node();
node2.data = 2;
Node node3 = new Node();
node3.data = 3;
node1.next = node2;
node2.next = node3;
delNode(node2);
Node current = node1;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
private static void delNode(Node node) {
Node next = node.next;
node.data = next.data;
node.next = next.next;
}
}
輸出
1 3
上面的代碼通過將后繼節點的數據復制到當前節點,從而刪除當前節點的方式完成了操作
注意:如果直接用下面的方式并不會改變鏈表(刪除node2,需要讓node1的next指向node3,下面的方法并沒有完成這個操作,只是node2變量指向了node2.next,但是node2節點還是被node1.next指向)
package com.lab2.test2;
public class DeleteNode {
public static void main(String[] args) {
Node node1 = new Node();
node1.data = 1;
Node node2 = new Node();
node2.data = 2;
Node node3 = new Node();
node3.data = 3;
node1.next = node2;
node2.next = node3;
node2=node2.next;
Node current = node1;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
private static void delNode(Node node) {
node=node.next;
}
}
輸出
1 2 3
不過如果是刪除首節點則可以,比如下面LinkedStack中的pop方法
package com.lab1.test1;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedStack<Item> implements Iterable<Item> {
private int n;
private Node first;
private class Node {
private Item item;
private Node next;
}
@Override
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Item next() {
Item item = current.item;
current = current.next;
return item;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (Item item : this) {
builder.append(item + " ");
}
return builder.toString();
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void push(Item item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public Item pop() {
if (isEmpty()) {
throw new NoSuchElementException("empty stack exception");
}
Item item = first.item;
first = first.next;
n--;
return item;
}
public static void main(String[] args) {
LinkedStack<String> stack = new LinkedStack<>();
System.out.println(stack);
System.out.println(stack.size());
System.out.println(stack.isEmpty());
stack.push("bill");
stack.push("jack");
stack.push("lucy");
System.out.println(stack);
System.out.println(stack.size());
System.out.println(stack.isEmpty());
stack.pop();
stack.pop();
System.out.println(stack);
System.out.println(stack.size());
System.out.println(stack.isEmpty());
}
}
Happy learning !!
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習