【问题标题】:How to save and get next and previous data in linked list?如何保存和获取链表中的下一个和上一个数据?
【发布时间】:2012-05-29 06:58:09
【问题描述】:

美好的一天。任何人都知道如何在 c 中使用链表来处理下一个和上一个数据?在我获得链表中的前一个数据后,我得到 NULL 值,如果我移动到右键(传递我想要获取的索引),则获取下一个数据没有任何问题,但是如果我将键移到左侧,我得到了NULL 值,即使我再次传递索引并获取我需要的数据。这是我的示例添加和获取链表代码。

typedef struct samp{
int idx;
char *name;
struct samp *next;
}sampLink;



sampLink *head=NULL,tail=NULL,test;
int addList(int idx,char *name){
  sampLink *tryi=NULL;
  tryi=(sampLink*)calloc(1,sizeof(sampLink));
  tryi->idx=idx;
  tryi->name=strdup(name);
  tryi->next=NULL;

  if(head==NULL){
    head=tryi;
    tail=tryi;
  }else{
    tail->next=tryi;
    tail=tail->next;
  }
  return 0;
}

sampLink *getList(int idx){
do{
    if(idx==head->idx){
      return head;
    }
    head=head->next;
  }while(head!=NULL);
  return head;
}

右移

void moveRight(){
int i=0;
test=getList(i);
i++;
}

对于左边的减号。希望有人能帮助我。谢谢

【问题讨论】:

  • 保存永久数据是什么意思?如果您希望数据持久化,则必须将其写入磁盘。
  • @nhahtdh 我的意思是我可以得到下一个和上一个,无论它的位置或索引是什么

标签: c linux list linked-list


【解决方案1】:

如果您真的想实现左/右移动,那么仅添加减号是行不通的。您需要实现一个双向链表,以便能够在两个方向上移动。

向左移动时可能会返回 NULL,因为向右移动时正在更改头指针,并且一旦更改头指针就会丢失一些节点,因为您的搜索不是双向的,因为它不是双向链表,因此返回结束节点(NULL)。

【讨论】:

    【解决方案2】:

    您的问题不是很清楚您要达到的目标。但是,您仍然可以在下面找到一些提示:

    1. 建议始终保持指向链表“头”的指针。但是,您不断在 moveRight 函数中对其进行修改。
    2. 如果要左右无缝移动,最好实现双向链表。

    使用您当前的单链表解决方案,您可以尝试下面的 getList 代码

    sampLink *getList(int idx)
    { 
      sampLink *temp = head;
      do{     
           if(idx==temp->idx)
           {       
             return temp;     
           }     
          temp=temp->next;   
    
        }while(temp!=NULL);   //Now, the function only keeps modifying the temp pointer rather than the head pointer, so each time you call the function, if idx is valid, it will return a pointer.
    
     return NULL; //If you had encountered a node which is having idx, you would have returned in the loop itself, so returning NULL here.
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 2021-09-26
      相关资源
      最近更新 更多