反转链表的每k个节点

发布于 2021-01-31 15:54:17

我正在准备进行技术面试,但我坚持编写此程序来反转链表的每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;
}
关注者
0
被浏览
122
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

    我喜欢您进行递归,尽管它可能不是最佳解决方案。从您的代码中可以看出,您在设计代码时会认为它很深。您距答案仅一步之遥。

    原因 :您忘记root在递归情况下返回新节点。

    if(temp!=NULL)
       noode->link=recrev(temp,c);
       // You need return the new root node here
       // which in this case is prev:
       // return prev;
     else
       return prev;
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看