Sword refers to Offer 18 (linked list 3). Delete the node of the linked list
Problem Description:
Given the head pointer of the singly linked list and the value of a node to be deleted, define a function to delete the node.
Returns the head node of the deleted linked list.
Example:
输入: head = [4,5,1,9], val = 5 输出: [4,1,9] 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
Input: head = [4,5,1,9], val = 1
Output: [4,5,9]
Explanation: Given the third node in your linked list with value 1, then after calling your function , the linked list should become 4 -> 5 -> 9.
Problem-solving ideas:Idea link
- Locating nodes : Traverse the linked list until head.val == val and jump out to locate the target node.
- Modify the reference : Set the predecessor node of the node cur as pre and the successor node as cur.next; then execute pre.next = cur.next to delete the cur node.
Algorithm flow :
- Special case handling: When the head node head should be deleted, just return head.next directly.
- Initialization: pre = head , cur = head.next .
- Positioning node: Jump out when cur is empty or the value of cur node is equal to val. Save the current node index, ie pre = cur. Traverse the next node, ie cur = cur.next.
- Delete node: If cur points to a node, execute pre.next = cur.next; if cur points to null, it means that the linked list does not contain a node whose value is val.
- Return value: Just return the head node head of the linked list.
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
//判断头结点的值是否就是目标值
if(head.val == val){
return head.next;
}
ListNode pre = head;
ListNode cur = pre.next;
//遍历链表
while(cur != null && cur.val != val){
pre = cur;
cur = cur.next;
}
//当现结点的值等于目标值时更改链表的next
if(cur.val == val){
pre.next = cur.next;
}
return head;
}
}