交换单链表中的特定元素

6 篇文章 0 订阅

给定一个单链表,和数字k,交换链表中头和尾的第k个节点。检查边界情况。

输入,输出如下:

Sample Input: 1->2->3->4->5->6->7->8 and K = 3
Sample Output : 1->2->6->4->5->3->7->8

Sample Input: 1->2->3->4->5->6->7->8 and K = 10
Sample Output: print error "LIST IS OF LESSER SIZE".


Given a singly link list and a number 'K', swap the Kth node from the start with the Kth node from the last. Check all the edge cases.

Sample Input: 1->2->3->4->5->6->7->8 and K = 3
Sample Output : 1->2->6->4->5->3->7->8

Sample Input: 1->2->3->4->5->6->7->8 and K = 10
Sample Output: print error "LIST IS OF LESSER SIZE".


可以在线性情况下用三个指针解决。

第一个指针指向开始的第k个元素

第二个指针指向从结尾开始的第k个元素

最后一个指针指向结尾

遍历链表,保存指针,在最后做交换,仅仅只用交换指针所指单元中的元素。

This can be done in line without first completely traversing the list to check the size. This can be done with 3 pointers.

One pointer is for the first element which is k from the start
the second pointer is for the element which is k from the end
the last pointer is to find the end.

Then you traverse the list save the pointers and do the swap at the end, you don't even have to mess with the links when swapping, just swap the values from the pointers you have saved from above.

#include <iostream>
using namespace std;
struct node
{
	int data;
	node* next;
};
node* exch_strandend_k(node* head,int k)
{
	node* ptr1,*ptr2,*ptr3=head;
	int count = 0;
	while (ptr3->next!=NULL)
	{
		count++;
		if (count == k)
		{
			ptr1 = ptr3;
			ptr2 = head;//ptr2和ptr3相隔k个元素 当ptr3指向末尾时 ptr2指向末尾以前的第k个元素
		}
		if (count>k)
		{
			ptr2 = ptr2->next;
		}
		ptr3 = ptr3->next;//ptr3指向链表末尾
	}
	if (count<k)//链表元素太少 报错并返回
	{
		cout<<"LIST IS OF LESSER SIZE"<<endl;
		return NULL;
	}
	if (ptr1!=NULL&&ptr2!=NULL)
	{
		int temp = ptr1->data;
		ptr1->data = ptr2->data;
		ptr2->data = temp;
		return head;
	}
	return NULL;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值