当我在 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;
}