【发布时间】:2016-07-29 12:37:22
【问题描述】:
给定一个单链表和一个位置,我试图删除一个特定位置的链表节点。 代码:
#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
【问题讨论】:
标签: c pointers linked-list singly-linked-list