2014-10-07 112 views
0

我是C新手,我想写一个链接列表,其中每个节点只包含一个int。结构的定义是可以的,但我也想编写方法来更新这个链表(在尾部添加元素并删除头元素)。 (我想能够读取最近添加的元素)创建一个链表来实现队列

我写了下面的函数,但我不知道应该在哪里发生这个函数以及如何实现它。任何人都可以帮助我吗?

typedef struct Node{ 
    Node next = NULL; 
    int number; 
} Node; 

void add_node(Node *LL,int val){ 
    // add node to the end of the linked list 
    new_node = (struct Node *)malloc(1*sizeof(struct Node)); 
    new_node->number = val; 
    Node n = *LL; 
    while (n.next != NULL){ 
     n = n.next; 
    } 
    n.next = new_node; 
} 

void delete_head(Node *LL){ 
    // update the head 
    *LL = LL->next; 
    //free? 
} 

void update_LL(*LL,int val){ 
    add_node(*LL,val); 
    delete_head(*LL); 
} 
+1

'节点下一= NULL;' - >'结构Node * next;'in C. – BLUEPIXY 2014-10-07 15:57:00

+1

正如所写,没有办法从'delete_head'内更新头部:它传递一个指向头节点的指针,但不知道该值的存储位置,因此无法更新它。你可以(正如很多人所说的那样)删除那个节点,但是跟踪头部的任何东西都需要更新到新的头部。 – 2014-10-07 16:06:58

回答

0

试着改变*LL = LL->next;Node *nextNode = LL->next;。 然后您可以拨打free(LL),然后再拨LL = nextNode

void delete_head(Node *LL){ 
    Node *nextNode = LL->next; 
    free(LL); 
    LL = nextNode; 
} 

这就释放了Node在头部和指针移动到链接列表中的下一个。

+3

因为'LL'实际上是一个局部变量,所以它不会*移动头部。 – 2014-10-07 16:00:58

+0

@Scott LL不是一个变量,它的一个指针 – 2014-10-07 16:05:46

+0

@MurtazaZaidi:Is是一个变量,其类型是一个指针。 – 2014-10-07 16:06:33

0

也许这个问题LinkedList - How to free the memory allocated using malloc

的副本基本上你存储指向要删除,否则你会泄漏内存,因为会在代码中任何地方存储位置没有引用的节点。

在你的delete_head函数中试试这个:

Node * temp = LL;

* LL = LL-> next;

free(LL);

希望这会有所帮助!

+2

'temp'和'* LL'不具有相同的类型;就此而言,'LL'和'LL-> next'都不会。 – 2014-10-07 16:03:01

+0

你确定吗?所有这些都是节点指针 – 2014-10-07 16:16:12

+0

不要相信我;问一个编译器。 – 2014-10-07 16:18:03

0

您需要在删除当前节点之前将链接保存到下一个节点。否则,你将无法引用链表的任何节点。现在,当您将链接备份到下一个节点时,可以释放由LL指向的当前节点,然后将LL指针指定给先前在临时指针中备份的下一个节点。

Node *temp = LL->next; 
free(LL); 
LL = temp; 
+0

因为'LL'实际上是一个局部变量,所以这将*不*移动头部。 – 2014-10-07 16:08:23

+0

@ScottHunter请查看这个http://www.nongnu.org/c-prog-book/online/x641.html – 2014-10-07 16:10:42

+0

如果指针作为参数传递,它指向一个内存位置,无论在该内存上执行什么操作无论在哪个范围内都是永久性的功能。 – 2014-10-07 16:11:28

1

我命名你的数据结构是这样的:

struct pointer 
      { 
      int field; 

      struct pointer *link; 
      }; 
typedef struct pointer cell; 

然后我们就可以使用此功能为你的需要:

void ad_an_element_at_the_end_of_the_list() 
     { 
     cell *p=NULL; 
     cell *ptr=head; 

     int value; 

     cout<<" Integer number to insert at the end of the list: "; 
     cin>>value; 
     p=(cell*)malloc(sizeof(cell)); 
     p->field=value; 
     p->link=NULL; 
     if(ptr==NULL) 
      { 
      ptr=p; 
      head=ptr; 

      }else 
       { 
       if(ptr->link==NULL) t 
        { 
        ptr->link=p; 
        head=ptr; 

        }else 
        { 
         while(ptr->link!=NULL) 
         { 
         ptr=ptr->link; 
         } 
        ptr->link=p; 

        } 
      } 
    }