从零开始的CPP(20)——创建链表,输出链表,删除链表

leetcode203

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

示例 1:

输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]

在C++中,如果两个指针指向同一个对象(在此上下文中,是链表中的节点),改变通过一个指针所进行的操作会影响到另一个指针看到的内容,因为它们实际上是共享同一块内存的。

通过影响指针的指向(prev->next),就可以改变链表的内容。

prev=prev->next/prev=curr只对指针移位,不改变链表

prev->next=curr改变了指针指向,所以会改变链表

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 temp(-1);
		temp.next = head;
		ListNode* prev = &temp;
		ListNode* curr = head;
		while (curr != nullptr) {
			if (curr->val == val) {
				prev->next = curr->next;
				curr = curr->next;
			}
			
			else {
				prev = prev->next;
				curr = curr->next;
			}
			//cout << head->next << endl;
		}
		head = temp.next;
		//head = prev;
		return head;
	}
	void showList(ListNode* temp) {
		ListNode* temp1 = temp;
		if (temp == nullptr) {
			cout << "nullptr!" << endl;
			return;
		}
		while (temp1->next != nullptr) {
			cout << temp1->val << "->";
			temp1 = temp1->next;
		}
		cout << temp1->val <<endl;
	}
};

int main() {
	Solution solution;
	vector<int> n = {1,4,1,3,5};
	ListNode* head = new ListNode(n[0]);
	ListNode* temp = head;
	for (int i = 1; i < n.size(); i++) {
		head->next = new ListNode(n[i]);
		head = head->next;
	}
	solution.showList(temp);
	int val = 1;
	ListNode* newhead = solution.removeElements(temp, val);
	solution.showList(newhead);
	return 0;
}
/*
int main() {
	Solution solution;
	vector<int> n = {1,4,1,3,5};
	ListNode head(n[0]);
	ListNode* temp = &head;
	ListNode* temp1 = &head;
	//另一种写法
	//ListNode* head = new ListNode(n[0]);
	//ListNode* temp = head;
	for (int i = 1; i < n.size(); i++) {
		temp1->next = new ListNode(n[i]);
		temp1 = temp1->next;
	}
	solution.showList(temp);
	int val = 1;
	ListNode* newhead = solution.removeElements(temp, val);
	solution.showList(newhead);
	return 0;
}
*/

给出了创建节点的两种方法 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值