链表相关题目

本文探讨了链表的各种操作,包括根据给定值删除节点、反转链表、找到链表的中间节点、寻找倒数第k个节点、合并两个升序链表、将小于特定值的节点前置、判断链表是否为回文、查找链表的交点、检测链表中的环以及寻找环的入口节点。同时,还涉及了复制带有随机指针的链表问题。
摘要由CSDN通过智能技术生成

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

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

//方法1
struct ListNode* removeElements(struct ListNode* head, int val)
{
	struct ListNode* prev = NULL;
	struct ListNode* cur = head;
	while (cur)
	{
		if (cur->val == val)
		{
			//头删
			if (cur == head)
				//if(prev==NULL)
			{
				head = cur->next;
				free(cur);
				cur = head;
			}
			else
			{
				//删除
				prev->next = cur->next;
				free(cur);
				cur = prev->next;
			}
		}
		else
		{
			prev = cur;
			cur = cur->next;
		}
	}
	return head;
}
//方法2
struct ListNode* removeElements(struct ListNode* head, int val)
{
	struct ListNode* tail = NULL;
	struct ListNode* cur = head;
	head = NULL;
	while (cur)
	{
		if (cur->val == val)
		{
			struct ListNode* del = cur;
			cur = cur->next;
			free(del);
		}
		else
		{
			//尾插
			if (tail == NULL)
			{
				head = tail = cur;
			}
			else
			{
				tail->next = cur;
				tail = tail->next;
			}
			cur = cur->next;
		}
	}
	if(tail)
	tail->next = NULL;

	return head;
}
//方法3
struct ListNode* removeElements(struct ListNode* head, int val)
{
	struct ListNode* tail = NULL;
	struct ListNode* cur = head;
	
	//哨兵位的头结点
	head = tail = (struct ListNode*)malloc(sizeof(struct ListNode));
	tail->next = NULL;

	while (cur)
	{
		if (cur->val == val)
		{
			struct ListNode* del = cur;
			cur = cur->next;
			free(del);
		}
		else
		{
				tail->next = cur;
				tail = tail->next;

			cur = cur->next;
		}
	}
	
	tail->next = NULL;

	struct ListNode* del = haed;
	head = head->next;
	free(del);
	return head;
}

2.给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

例如:输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]

//方法1
struct ListNode* reverseList(struct ListNode* head)
{
	struct ListNode* newhead = NULL;
	struct ListNode* cur = head;
	while (cur)
	{
		struct ListNode* next = cur->next;

		//头插
		cur->next = newhead;
		newhead
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值