Leetcode-删除链表中的节点

55.删除链表中的节点

题目内容:

代码及思路:

第一次做题的时候按照之前做题的思路,给定一个列表LinkNode* head和一个目标节点数target,则可以实现题目中的要求:

/**
 * 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 target){
	if(head==nullptr)
        return nullptr;
    LinkNode* p1 = nullptr;
	p1 = head;
	LinkNode* pnext = p1->next;
	while (p1 != nullptr)
	{
		if (pnext != nullptr)
		{
			if (pnext->val == target)
			{
				p1->next = pnext->next;
				pnext = p1->next->next;

			}
			else
			{
				p1 = p1->next;
				pnext = p1->next;
			}
		}
	}
    return head;
  }
}

然后再看题目,题目太流氓了,直接给出的是需要删除的节点node,所以直接用覆盖的思想就可以写成:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        if(node==nullptr)
            return;
        //利用下一个节点来覆盖当前节点
        node->val=node->next->val;
        node->next=node->next->next;
        
    }
};

这操作太骚了= =

猜你喜欢

转载自blog.csdn.net/larklili/article/details/89670916