开发者

Removing a node of a linked list in a recursive function

After spending more than 10 hrs, the following code is developed:

struct stockRecord* temp = NULL;
struct stockRecord* head = NULL;
struct stockRecord* prevptr = NULL;
struct stockRecord* recurfun(struct stockRecord* list) {

   temp = list;
   if (head == NULL) head = temp;
   if (temp == NULL) {
      return head;
   } else {
      /*first node*/
      if (prevptr == NULL) {

     开发者_如何学Python    if (strstr(temp->name, "ABC-") != NULL) {

            temp = temp->next;

            head = temp;
        prevptr = head;

         }  
      }
      /*last node*/
      if (temp->next == NULL) {
         if (strstr(temp->name, "ABC-") != NULL) {
            prevptr->next = NULL;

         }
         return head;
      }
      /*middle node*/

         if (strstr(temp->name, "ABC-") != NULL) {
               prevptr->next = temp->next;

         } else {
               if (prevptr != NULL) {
                 prevptr = temp;
               } else {
                 prevptr = head;
               }
         }

      return recurfun(temp->next);      

   }

The problem is, when first node and the second node also contains "ABC-", the function only remove the first node, the second node still can't be removed.

What's the problems of my code?


Suppose you start out with 1->2->3

After you remove the first node, you set prevptr, head, and temp to all point to 2.

Then at the end of the function you recursively call it on temp->next which points to 3.

The result is that you are skipping the second node when you remove the first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜