c - 从单链表中删除节点C编程

标签 c computer-science singly-linked-list

当我在VS和代码块中构建程序时没有任何问题。然而,当我运行它时,它要么在我输入索引号后崩溃,要么只是无限地显示字母......

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


// list_node structure

typedef struct list_node{
    int item;
    struct list_node *next;
}ListNode;
//call functions that will be used 

void printNode(ListNode *head);
int removeNode(ListNode **ptrhead, int index);
ListNode *findNode(ListNode *head, int index);

int main(){
    int index,value;
    ListNode *head=NULL;
    ListNode *temp;
    //build the list  

    printf("Enter a value:");
    scanf("%d",&value);
    do{
              temp->item=value;
        if(head==NULL){
            head=(struct list_node *)malloc(sizeof(ListNode));
            temp=head;
        }
        else{
            temp->next=(struct list_node *)malloc(sizeof(ListNode));
            temp=temp->next;
        }
        printf("Enter a value:");
        scanf("%d",&value);

    }while(value!=-1);

    printf("Enter the index: ");
    scanf("%d",&index);
    // remove the node at the position indexed

    // when I used debugger, I saw it didn't execute this step. Maybe there's something wrong with it....

    removeNode(&head,index);

    printNode(head);

    return 0;
}


void printNode(ListNode *head){
    if (head==NULL)
        exit(0);
    while(head!=NULL){
        printf("%d",head->item);
        head=head->next;
    }
    printf("\n");
}

ListNode *findNode(ListNode *head,int index){
    if(head==NULL||index<0)
        return NULL;
    while(index>0){
        head=head->next;
        index--;
    }
    return head;
}


int removeNode(ListNode **ptrhead,int index){
    ListNode *pre,*cur,*temphead;

    temphead=*ptrhead;

    if(findNode(temphead,index)!=NULL){
        pre=findNode(temphead,index);
        cur=pre->next;
        temphead->next=cur;
        return 0;
    }
    else
        return -1;
}

最佳答案

prev=NULL;
cur=head;
/* traverse the list until you find your target */
while (cur != NULL && cur->id != search_id) {
  prev=cur;
  cur=cur->next;
}
/* if a result is found */
if (cur != NULL) {
  /* check for the head of the list */
  if (prev == NULL)
    head=cur->next;
  else
    prev->next=cur->next;  
  /* release the old memory structure */
  free(cur);
}

怎么了老兄......我希望你能明白......:)

关于c - 从单链表中删除节点C编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15585645/

相关文章:

javascript - 在 JavaScript 中反转链表的策略

c++ - 我试图按升序将两个链表合并为 1 个链表

c - 这个c代码的o/p是什么?为什么?

C#-C进程间通信

computer-science - NP问题为什么这样称呼(以及NP难题和NP难题)?

c - 我应该学习汇编语言或 C 来理解 "real programming"是如何工作的吗?

c++ - 类体之外的成员函数定义导致错误

c - 返回大于数组第一个索引的数字数量的递归函数

c - 如何用 C 创建迷你基准程序

functional-programming - 对于定点组合器 Y,\x.f(xx) 是什么