C中的更多链接列表

non*_*one 12 c pointers structure linked-list

在我开始我想讲清楚,我不想回答我的家庭作业的问题,我只是想,如果有人能真正解释正是我的教练在这种分配(最好是简单化版)要求,也许一个有用的推动正确的方向.我在这个话题上遇到了很多麻烦,每当我问导师时,我发现他比我更困惑我.

所以,这是作业:

1.添加一个新函数insertN(struct list*x,int num,int pos,int n),它将在pos位置插入n个整数num的副本,如果可能的话(如果pos太大,采取适当的行动) .我在这里感到困惑的主要是他所说的位置pos.

这是我正在使用的代码 - 由我的老师编写,我必须修改它.

#include<stdio.h>
#include<stdlib.h>

struct list {
    int data;
    struct list * next;
        };

struct list *slist;

/*adds a node at the end of the linked list*/
void insert(struct list *x,int num){
  /*if the list is empty*/
  if(x==NULL){
    /*create first node*/
    slist=malloc(sizeof(struct list));
    slist->data=num; 
    slist->next=NULL;
    }
  else{
    /*go to the last node*/
    while(x->next!=NULL) x=x->next;
    /*add node at the end*/
      x->next=malloc(sizeof(struct list));
      x->next->data=num;
      x->next->next=NULL;

  }
}


void display(struct list *x){
  /*traverse the entire linked list*/
  while(x!=NULL){
    printf("%d->",x->data);
    x=x->next;
  }
  printf("NULL");
}

void reverse(struct list *x){
  struct list *prev,*rev,*temp;

  prev=x;
  rev=NULL;

  while(prev!=NULL){
    temp=rev;
    rev=prev;
    prev=prev->next;
    rev->next=temp;
  }
  slist=rev;
}

void search(struct list *x,int a){
struct list *runner;
int found=0;
  for(runner=x;runner!=NULL;runner=runner->next){
  if(runner->data==a){
    printf("data found"); 
    found=1;
break;
  }
  }
if(found==0) printf("data not found");

}

main(){
  int number,a;

  slist=NULL;/*empty linked list*/

  printf("Enter the element for data part:");
  scanf("%d",&number);
  insert(slist,10);
  insert(slist,number);

  insert(slist,20);

  display(slist);
  printf("\n");

  reverse(slist);

  display(slist);
  printf("\nEnter the element for searching:");
  scanf("%d",&a);
  search(slist,a);
  printf("\n");
  getchar();
  getchar();
}
Run Code Online (Sandbox Code Playgroud)

再说一遍,我不期望找到问题的答案,只是解释和推动正确的方向.

Ber*_*ann 3

通过说“在位置 5”,他的意思是他希望您迭代(“遍历”)列表 5 个步骤,然后插入那里。

如果您有这样的列表的引用:

struct list * current;
Run Code Online (Sandbox Code Playgroud)

单个步骤可以这样完成:

current = current -> next;
Run Code Online (Sandbox Code Playgroud)

现在你要做的就是这样做,直到到达正确的位置,然后插入那里。