Reference from: "Sword Pointing Offer - Famous Enterprise Interviewer Talking About Typical Programming Questions"
Title : Deleting a Linked List Node in O(1) Time
Given the head pointer of a singly linked list and a node pointer, define a function to delete the node in O(1) time.
Main idea :
There are three cases:
1. The node to be deleted is not the tail node: replace the node to be deleted with its next node.
2. The linked list has only one node, that is, the head node is the node to be deleted: directly set the head node to null.
3. The node to be deleted is the tail node: find the previous node of the node to be deleted, and set the next node of the found node to null.
Key points : node replacement, special nodes (head node and tail node)
Time Complexity : O(1) on average
public class DeleteNodeInList
{
public static void main(String[] args)
{
int[] data = {3, 4, 5, 7};
ListNode pHead = LinkedListData.GenerateDataByArray(data);
ListNode deletedNode5 = pHead.next.next; //5
ListNode deletedNode7 = pHead.next.next.next; //7
ListNode result = deleteNode(pHead, pHead);
while (result != null)
{
System.out.println(result.val);
result = result.next;
}
}
private static ListNode deleteNode(ListNode head, ListNode deletedNode)
{
if (head == null || deletedNode == null) return null;
//删除的结点不是尾结点
if (deletedNode.next != null)
{
//将要删除的结点替换成它的下一个结点
ListNode nextNode = deletedNode.next;
deletedNode.val = nextNode.val;
deletedNode.next = nextNode.next;
}
//链表只有一个结点,即头结点就是要删除的结点
else if (head.val == deletedNode.val)
{
head = null;
}
//删除的结点是尾结点
else
{
ListNode pNode = head;
//找到要删除的结点的前一个结点
while (pNode.next.val != deletedNode.val)
{
pNode = pNode.next;
}
pNode.next = null;
}
return head;
}
}
class ListNode
{
int val;
ListNode next = null;
ListNode(int val)
{
this.val = val;
}
}
class LinkedListData
{
/**
* 根据数组生成链表
* @param data
* @return
*/
public static ListNode GenerateDataByArray(int[] data)
{
ListNode head = new ListNode(data[0]);
ListNode currentNode = head;
for (int i = 1; i < data.length; i++)
{
ListNode next = new ListNode(data[i]);
currentNode.next = next;
currentNode = next;
}
return head;
}
}