【算法与数据结构】203、LeetCode移除链表元素

所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解

题目

在这里插入图片描述

一、解题思路

  思路分析:这道题需要注意一个特殊情况,当删除的是头结点时,直接删除就找不到整个链表。因此我们加入一个假节点,代替头结点的作用,即使删除了也能找到整个链表,同时C++需要手动释放内存,使用delete删释放内存。
【算法与数据结构】复杂度和一些简单算法  程序如下

class Solution {
    
    
public:
	ListNode* removeElements(ListNode* head, int val) {
    
    
		ListNode* FakeNode = new ListNode(0, head);
		ListNode* cur = FakeNode;
		while (cur != NULL && cur->next != NULL) {
    
    
			if (cur->next->val == val) {
    
    
				ListNode* tmp = cur->next;
				cur->next = cur->next->next;
				delete tmp;
			}
			else {
    
    
				cur = cur->next;
			}
		}
		head = FakeNode->next;
		delete FakeNode;
		return head;
	}
};

复杂度分析:

  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)

  再写这份代码是还借鉴了两篇博文,当时想将数组传入函数,在函数内部使用sizeof计算数组长度,后面更改了思路,参考C/C++ 数组作为参数传递到函数后,使用 sizeof 产生的问题。在创建链表时,参考C++ 详解创建链表过程

完整代码

# include <iostream>
using namespace std;

struct ListNode {
    
    
	int val;
	ListNode *next;
	ListNode() : val(0), next(nullptr) {
    
    }
	ListNode(int x) : val(x), next(nullptr) {
    
    }
	ListNode(int x, ListNode *next) : val(x), next(next) {
    
    }
};
 
class Solution {
    
    
public:
	ListNode* removeElements(ListNode* head, int val) {
    
    
		ListNode* FakeNode = new ListNode(0, head);
		ListNode* cur = FakeNode;
		while (cur != NULL && cur->next != NULL) {
    
    
			if (cur->next->val == val) {
    
    
				ListNode* tmp = cur->next;
				cur->next = cur->next->next;
				delete tmp;
			}
			else {
    
    
				cur = cur->next;
			}
		}
		head = FakeNode->next;
		delete FakeNode;
		return head;
	}
};

ListNode* ChainGenerator(int arr[], int len) {
    
    
	ListNode *head = new ListNode(arr[0], NULL);	
	ListNode* p = head;
	for (int i = 1; i < len; i++) {
    
    
		ListNode* pNewNode = new ListNode(arr[i], NULL);
		p->next = pNewNode; // 上一个节点指向这个新建立的节点
		p = pNewNode; // p节点指向这个新的节点
	}
	return head;
}

void my_print(ListNode* head, string str) {
    
    
	cout << str << endl;
	ListNode *cur = head;
	while (cur != NULL) {
    
    
		cout<< cur->val <<' ';
		if (cur->next == NULL) break;
		cur = cur->next;		
	}
	cout << endl;
}

int main()
{
    
    
	int arr[] = {
    
     1,2,6,3,4,5,6 };
	int len = sizeof(arr) / sizeof(int);
	int target = 6;
	Solution s1;
	ListNode* head = ChainGenerator(arr, len);
	my_print(head, "目标链表:");
	head = s1.removeElements(head, target);
	my_print(head, "删除目标元素后的链表:");
	system("pause");
	return 0;
}

end

猜你喜欢

转载自blog.csdn.net/qq_45765437/article/details/131083844