您的位置:首页 > 其它

交换单链表中的特定元素

2013-05-16 21:46 162 查看
给定一个单链表,和数字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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐