0203 0237

作者: 日光降临 | 来源:发表于2019-02-13 22:22 被阅读0次
  1. Remove Linked List Elements
    C语言版
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
    dummy->next = head;
    head = dummy;
    while(head->next!=NULL){
        if(head->next->val == val)
            head->next = head->next->next;
        else
            head = head->next;
    }
    return dummy->next;
}

Java版,dummy节点真的是很有技巧。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        while(head.next!=null){
            if(head.next.val == val)
                head.next = head.next.next;
            else
                head = head.next;
        }
        return dummy.next;
    }
}
  1. Delete Node in a Linked List
    The linked list will have at least two elements.
    All of the nodes' values will be unique.
    The given node will not be the tail and it will always be a valid node of the linked list.
    Do not return anything from your function.
    该题没有提供链表的头节点,只是提供了要被删除的节点的指针或者引用
    C语言版
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
void deleteNode(struct ListNode* node) {
    node->val = node->next->val;
    node->next = node->next->next;
}

Java版

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

相关文章

网友评论

      本文标题:0203 0237

      本文链接:https://www.haomeiwen.com/subject/njmjeqtx.html