【发布时间】:2011-10-31 13:47:41
【问题描述】:
我正在准备一次技术面试,我一直在编写这个程序来反转链表的每 k 个节点。
例如
1->2->3->4->5->6 //Linked List
2->1->4->3->6->5 //Output for k=2
编辑:
这是我的代码。我只得到 6->5 作为输出。
struct node* recrev(struct node* noode,int c)
{
struct node* root=noode,*temp,*final,*prev=NULL;
int count=0;
while(root!=NULL && count<c)
{
count++;
temp=root->link;
root->link=prev;
prev=root;
root=temp;
}
if(temp!=NULL)
noode->link=recrev(temp,c);
else
return prev;
}
感谢任何帮助。谢谢。
编辑:我尝试如下实现 Eran Zimmerman 的算法。
struct node* rev(struct node* root,int c)
{
struct node* first=root,*prev,*remaining=NULL;
int count=0;
while(first!=NULL && count<c)
{
count++;
prev=first->link;
first->link=remaining;
remaining=first;
first=prev;
}
return remaining;
}
struct node* recc(struct node* root,int c)
{
struct node* final,*temp,*n=root,*t;
int count=0;
while(n!=NULL)
{
count=0;
temp=rev(n,c);
final=temp;
while(n!=NULL && count<c)
{
printf("inside while: %c\n",n->data); // This gets printed only once
if(n->link==NULL) printf("NULL"); //During first iteration itself NULL gets printed
n=n->link;
final=final->link;
count++;
}
}
final->link=NULL;
return final;
}
【问题讨论】:
-
我已经编辑了我的问题,添加了我的代码。
-
+1:查看您的代码后,我相信您会仔细考虑自己的答案,尽管它可能不是最佳答案。
标签: c algorithm linked-list