剑指offer删除链表节点O(1)算法

题目描述:

给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点。

解题思路:

(1)常规思路:

在单向链表中删除一个结点,最常规的做法无疑是从链表的头结点开始,顺序遍历查找要删除的结点,并在链表中删除该结点。这种思路由于需要顺序查找,时间复杂度自然就是O(n)。
在这里插入图片描述

(2)正确思路:

我们可以很方便地得到要删除的结点的一下结点。因此,我们可以把下一个结点的内容复制到需要删除的结点上覆盖原有的内容,再把下一个结点删除,就相当于把当前需要删除的结点删除了。
  在这里插入图片描述

#include <iostream>
using namespace std;




class ListNode {
public:
    int val;
    ListNode *next;
    ListNode(int val) {
        this->val = val;
        this->next = NULL;
    }
};
class Solution
{
public:
	void deleteNode(ListNode **head, ListNode *node)
	{
		// write your code here
		if (node == NULL)
			return;

		if (node->next != NULL)  //拷贝下一个节点的值与指针
		{
			ListNode *pNext = node->next;
			node->val = pNext->val;
			node->next = pNext->next;
			delete pNext;
			pNext = NULL;
		}

		else if (*head == node)  //删除的节点是头节点
		{
			delete node;
			node = NULL;
			*head = NULL;
		}

		else                  //删除的是尾节点
		{
			ListNode *pNode = *head;
			while (pNode->next != node)
			{
				pNode = pNode->next;
			}

			pNode->next = NULL;
			delete node;
			node = NULL;
		}
	}
};

//左边的测试案例,大家可以随便测。
int main()
{
	ListNode *n = new ListNode(10);
	ListNode *n1 = new ListNode(11);
	ListNode *n2= new ListNode(12);
	ListNode *n3 = new ListNode(13);
	ListNode *n4 = new ListNode(14);
	ListNode *n5 = new ListNode(15);
	ListNode *n6 = new ListNode(16);
	n->next = n1;
	n1->next = n2;
	n2->next = n3;
	n3->next = n4;
	n4->next = n5;
	n5->next = n6;
	Solution s;
	s.deleteNode(&n,n6);
	ListNode * head = n;
	while (head != NULL)
	{
		cout << head->val << endl;
		head = head->next;
	}

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值