手撕链表~~

链表的创建以及实现增删改查功能,利用了哑节点把头节点“大众化”

//创建结构体
struct Node {
	int val;
	Node* next;
	Node(int val) {
		this->val = val;
		this->next = nullptr;
	}
};
//全局变量
Node* head;
Node* tail;
Node* dummyhead;
//用数组传参创建链表
Node* createList(vector<int>&a) {
	for (int i = 0; i < a.size(); i++) {
		Node *newnode = new Node(a[i]);
		if (!head) {
			head = newnode;
			tail = newnode;
		}
		else {
			tail->next = newnode;
			tail = newnode;
		}
	}
	return head;
}
//打印
void print(Node* head) {
	while (head) {
		cout << head->val<<" ";
		head = head->next;
	}
	printf("\n");
	return;
}
//增加:在index个节点前加节点val(index从0计数)
Node* add(int val,int index) {
	if (!head) return head;
	dummyhead = new Node(-1);
	Node* newnode = new Node(val);
	dummyhead->next = head;
	Node* cur = dummyhead;
	while (index) {
		cur = cur->next;
		index--;
	}
	newnode->next = cur->next;
	cur->next = newnode;
	return dummyhead->next;
}
//删除值为val的所有节点
Node* deleteNode(int val) {
	if (!head) return head;
	dummyhead = new Node(-1);
	dummyhead->next = head;
	Node* cur = dummyhead;
	while (cur->next) {
		if (cur->next->val==val) {
			cur->next = cur->next->next;
		}
		else {
			cur = cur->next;
		}
	}
	return dummyhead->next;
}
//改:将节点nums1改为nums2
Node* changeNode(int nums1, int nums2) {
	if (!head) return head;
	Node* p = head;
	while (p) {
		if (p->val == nums1) {
			p->val = nums2;
		}
		p = p->next;
	}
	return head;
}
//查找
bool get(int target) {
	if (!head) return head;
	dummyhead = new Node(-1);
	dummyhead->next = head;
	while (head) {
		if (head->val == target) {
			return 1;
		}
		head = head->next;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值