链接列表插入简单

时间:2017-10-28 00:37:56

标签: c linked-list

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

typedef struct node{
   int key;
   struct node* next;
} node_t;

typedef node_t* node_ptr;

void main()
{
    node_ptr p = NULL;
    node_ptr listhead =NULL;

    /*need to create a listhead with key = 1,2,3..10*/

    int i; 
    for (i =1; i<= 10;i ++) 
    {
       node_ptr temp;
       p =(node_ptr)malloc(sizeof(node_t));
       p->key = i;
       p->next = NULL;
       if( list_head == NULL ) 
       {
         list_head= p;   
       }
       else
       {
       temp = listhead;

         while(temp->next != NULL)
         {
           temp = temp->next;
         }
         temp->next =  p;
       }
    }
}

我仍然对链表感到困惑,我不确定我是否做得正确并且确定它是错的,有人可以帮帮我吗?这只是 一个练习题:) 并且还提升了node_ptr listhead = NULL的行;在问题中给出,所以我不能改变上面的东西。

顺便说一下,问题是要求将1,2,3..10键插入列表头。

1 个答案:

答案 0 :(得分:2)

“插入”可能意味着插入列表的开头而不是列表中的某个位置或列表的末尾。对于这个赋值,什么是“插入”应该是什么意思?

使用for循环和次要更改的示例代码,例如使用node_ptr而不是node_t *来对应赋值typedef,以及int main()而不是void main()。

#include <stdlib.h>

typedef struct node{
    int key;
    struct node* next;
} node_t;

typedef node_t* node_ptr;
typedef node_t ** node_ptr_ptr;

int main()
{
    node_ptr list_head = NULL;
    node_ptr p;
    /* ptr to either list_head or to last node.next */
    node_ptr_ptr pptemp;
    int i; 
    /* create a list with keys = 1,2,3..10 */
    for (i = 1; i <= 10; i++) 
    {
        p = (node_ptr)malloc(sizeof(node_t));
        p->key = i;
        p->next = NULL;
        for(pptemp = &list_head; *pptemp != NULL; pptemp = &(*pptemp)->next);
        *pptemp =  p;
    }
    return 0;
}

使用指向节点指针的指针的备用版本。这消除了对list_head == NULL的初始检查。它超出了你现在用于作业的范围,但知道如何做到这一点在以后的作业中可能会有用。

#include <stdlib.h>

typedef struct node{
    int key;
    struct node* next;
} node_t;

typedef node_t* node_ptr;
typedef node_t ** node_ptr_ptr;

int main()
{
    node_ptr list_head = NULL;
    node_ptr p;
    /* ptr to either list_head or to last node.next */
    node_ptr_ptr pptemp = &list_head;
    int i; 
    /* create a list with keys = 1,2,3..10 */
    for (i = 1; i <= 10; i++) 
    {
        p = (node_ptr)malloc(sizeof(node_t));
        p->key = i;
        p->next = NULL;
        *pptemp = p;
        pptemp = &p->next;
    }
    return 0;
}

对于这种特殊情况,由于temp(或pptemp)在main中,它只需要初始化一次并且每个循环前进一次:

{{1}}
相关问题