給定單向鏈表和位置,我試圖刪除特定位置上的鏈接列表節點。 CODE:刪除鏈接列表中給定位置的節點
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void printList(struct node* head_ref)
{
//struct node* head_ref = (struct node*)malloc(sizeof(struct node));
if(head_ref == NULL)
printf("The list is empty");
while(head_ref!=NULL)
{
printf("%d\n",head_ref->data);
head_ref = head_ref->next;
}
}
void insert_beg(struct node **head_ref,int new_data)
{
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
void delete(struct node **head_ref,int position)
{
int i=1;
if(*head_ref == NULL)
return;
struct node *tails,*temp = *head_ref;
if(position == 0)
{
*head_ref = temp->next;
free(temp);
return;
}
while(temp->next!=NULL)
{
tails = temp->next;
temp = temp->next;
if(i == position)
{
tails->next = temp->next;
free(temp);
return;
}
i++;
}
}
int main()
{
struct node *head = NULL;
insert_beg(&head,36);
insert_beg(&head,35);
insert_beg(&head,34);
insert_beg(&head,33);
printList(head);
int position;
printf("Enter the position of the node u wanna delete\n");
scanf("%d",&position);
delete(&head,position);
printf("\n");
printList(head);
}
每當我試圖刪除上述位置0的節點,我在那個特定位置,而不是什麼都不讓0。我能知道我要去哪裏嗎? 對於如我的名單是:33 34 35 36 我的輸出:33 0 35 36(嘗試刪除節點1) 有效輸出:33 35 36