題目描述
給定單向鏈表的頭指針和一個節點指針,定義一個函數在O(1)時間刪除該節點。
編程思路
時間複雜度
程序代碼(Java語言)
package 刪除鏈表結點;
public class Test {
public static class ListNode {
public int data;
public ListNode next;
public ListNode(int data,ListNode next) {
this.data = data;
this.next = next;
}
}
public static void deleteNode(ListNode node,ListNode head) {
if(node.next == null) {
while(head.next != node) {
head = head.next;
}
head.next = null;
} else if(head == node) {
head = null;
} else {
node.data = node.next.data;
node.next = node.next.next;
}
}
public static void main(String[] args) {
ListNode tail = new ListNode(1,null);
ListNode b = new ListNode(2,tail);
ListNode a = new ListNode(3,b);
ListNode head = new ListNode(4,a);
deleteNode(b,head);
while(head != null) {
System.out.println(head.data);
head = head.next;
}
}
}