讨论/《画解剑指 Offer》 - 剑指 Offer 18. 删除链表的节点/
《画解剑指 Offer》 - 剑指 Offer 18. 删除链表的节点
共 3 个回复
struct ListNode* deleteNode(struct ListNode* head, int val){
    if(head == NULL){
        return NULL;
    }
    struct ListNode*temp = head;
    struct ListNode*ret = head;
    if(head->val == val){
        return head->next;
    }
    while(head){
        if(head->val == val){
            temp->next = head->next;
        }
        temp = head;
        head = head->next;
    }
    return ret;
}
/**
 * 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 dummy = new ListNode(-1);
        dummy.next=head;
        ListNode cur = dummy;
        while(cur.next!=null){
            if(cur.next.val==val){
                cur.next=cur.next.next;
                break;
            }
            cur=cur.next;
        }
        return dummy.next;
    }
}

goby

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteNode(self, head: ListNode, val: int) -> ListNode:
        if head.val == val:
            head = head.next
        pre = head
        cur = head.next
        while(cur):
            if cur.val == val:
                pre.next = cur.next
                break
            pre = pre.next
            cur = cur.next   
        return head