2011-06-05 127 views
2

这里是我到目前为止的代码:如何从链表中删除节点?

struct stockRecord { 
    int code; 
    char name[MAXNAMELEN]; 
    struct stockRecord* next; 
}; 

struct stockRecord* temp = NULL; 
struct stockRecord* head = NULL; 
struct stockRecord* prevptr = NULL; 

struct stockRecord* resfun(struct stockRecord* list) 
{ 
    temp = list; 
    if (head == NULL) head = list; 
    if (temp == NULL) { 
     return head; 
    } else { 
     if (prevptr == NULL) { //first node 
     if (strstr(temp->name, "ABC-") != NULL) { 
      temp = temp->next; //remove the current node 
     } 
     } 
     prevptr = list; 

     if (temp->next == NULL) { 
     return head; 
     } else { 
     return resfun(temp); 
     } 
    } 
} 

我不知道如何删除一个节点,并重新连接相邻节点。然后我需要将头节点返回到主函数。

请任何人都可以帮忙吗?

谢谢。

+0

你的代码与你的问题有什么关系? – 2011-06-05 12:30:23

+1

我已经开始编辑你的问题,以便更清楚地说出我认为你在问什么......如果我错了,请随时加入并改正我,并请提前接受我的意见。现在,要回答... – corlettk 2011-06-05 12:40:27

+0

真的应该开始使用局部变量! – 2011-06-05 12:42:00

回答

3

维加,

从单链表中删除第一个元素,你真正需要做的是“忘记”的第一个元素(头)。

用于去除第一个节点的一般过程是:

  1. 如果节点被动态分配 (它们几乎是永诺在 链表)然后释放分配给该节点的存储器 。
  2. 通过将它“向下移动”一个而“忘记”了头部。我总是把链接列表看作是点击向下页面的点。

在列表中的中间删除节点的一​​般过程是:

  1. 自由存储器
  2. 链路高于此一对一的下面这一个入口。
    • I.e. prev->未来=这个 - >未来

除去最后一个节点的一般程序是(我敢打赌,你能猜到):

  1. 可用内存
  2. prev->未来= null; (其中prev是第二个最后节点)

递归与它无关。


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

    #define SIZE_OF_NAME 12 
    #define SUCCESS 0 

    typedef struct Stock* stock; 

    struct Stock { 
     int code; 
     char name[SIZE_OF_NAME]; 
     stock next; 
    }; 

    stock head = NULL; 
    stock prev = NULL; 

    stock StripABC(stock curr) 
    { 
     if (strstr(curr->name, "ABC-") != NULL) { 
     // the first name contains "ABC-", so strip it. 
     head = head->next; 
     curr = head; 
     } 
     return head; 
    } 

    int main(int argc, char *argv[]) 
    { 
     struct Stock a, b; 
     a.code = 1; strcpy(a.name, "ABC-"); 
     b.code = 2; strcpy(b.name, "Widget"); 
     head = &a; 
     head->next = &b; 

     StripABC(head); 

     printf("head->name: %s\n", head->name); 

     return SUCCESS; 
    } 

祝你好运。顺便说一句,对于ansi-c程序员来说,链表仍然是“交易中的股票”。我仍然经常与他们合作;-)

干杯。基思。

1

你的代码有点难以遵循。但我会尽力帮助

这条线:

temp = temp->next; //remove the current node 

实际上并没有从列表中删除的节点。它应该是这个样子

prev->next = temp->next; // link the previous node past the current node 
free(temp); // now that nothing is pointing to temp, you can deallocate the memory 
return head; // we found our node, return the head of the list 

此外,你应该添加一些代码来检查哪里要删除的节点位于列表的头的情况。在这种情况下,不需要重新链接节点。只需将头指针设置为列表中的下一个节点,然后删除temp。

+0

Alan,有一件事......这就是C ......只要你不试图在释放后尝试访问那个位置的内存,就可以安全地释放你仍然持有指针的内存。尽管如此,你的方式可能是更安全(最好)的做法,现在我想到了。干杯。基思。 – corlettk 2011-06-05 13:16:42