题意
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
题解
//C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(head->val == val)
return head->next;
ListNode* pre = head;
ListNode* p = head->next;
while(p != NULL && p->val != val){
pre = p;
p = p->next;
}
if(p != NULL) pre->next = p->next;
return head;
}
};
也可以用一个指针
//Java
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head == null) return null;
if (head.val == val) return head.next;
ListNode cur = head;
while (cur.next != null && cur.next.val != val)
cur = cur.next;
if (cur.next != null)
cur.next = cur.next.next;
return head;
}
}