题目描述:
标签:链表
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
说明:
- 题目保证链表中节点的值互不相同
- 若使用 C 或 C++ 语言,你不需要
free
或delete
被删除的节点
代码:
思路分析:
掌握以下删除链表的表达式cur.next = cur.next.next
/**
* 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) {
ListNode cur = head;
if(head.val == val){
return head.next;
}
while(cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
return head;
}
cur = cur.next;
}
return head;
}
}