链表常用操作(笔试面试经常遇到)

笔试面试的时候经常会出现操作链表的题目,一般都会要求直接写代码,所以笔面试之前熟悉一下链表各种操作还是有帮助的,我大概实现了一些一下操作。

一 、先来个最简单的反转链表

void reversal(listNode* head)//reverse the list
	{
		listNode* before = NULL;
		listNode *current = head;
		listNode *temp = head;
		while(current != NULL)
		{
			listNode* next = current->next;
			current->next = before;
			before = current;
			current = next;
		}
		head = before;
	}

二、找到链表的中点

listNode* find_mid(listNode* head)
	{
		listNode* first = head;
		listNode* second = head;
		while(second != NULL)
		{
			second = second->next;
			if(second != NULL)
			{
				first = first->next;
				second = second->next;
			}
		}
		return first;
	}

类似地,还可以实现找到三分之一处节点等等。

三、找到倒数第k个节点

listNode* func(listNode* root, int k)
	{
		listNode* first = root;
		listNode* second = root;
		while(k--)
		{
			if(second != NULL)
				second = second->next;
			else break;
		}
		if(second == NULL)
			return NULL;
		else
		{
			while(second != NULL)
			{
				first = first->next;
				second = second->next;
			}
			return first;
		}
	}
四、判断链表中是否有环

bool judge_circle(listNode* head)
	{
		listNode* first = head, *second = head;
		if(head == NULL) return false;
		do
		{
			second = second->next;
			if(second != NULL)
			{
				first = first->next;
				second = second->next;
			}
		}
		while(second != NULL && second != first && first != second);
		return first == second;
	}
五、1-〉2->3->4->5->6-> 变为 1->6->2->5->3->4(首尾交替取),稍微难的


void reorder()//12345 重排序为15243
	{
		listNode* current = head;
		while(true)
		{
			listNode* next = current->next;
			listNode* findTheEnd = next;
			listNode* tempPre = findTheEnd;
			if( next == NULL||next->next == NULL )break;
			while(findTheEnd->next != NULL)
			{
				tempPre = findTheEnd;
				findTheEnd = findTheEnd->next;
			}
			tempPre->next = NULL;
			current->next = findTheEnd;
			findTheEnd->next = next;
			current = next;
			next = next->next;
		}
	}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值