问题
The following code works fine for all the functions except the deleteEnd function. When i execute the program all the functions perform the tasks they are supposed to but the deleteEnd function does nothing. There is no change in the linked list on executing the deleteEnd function. Please Help!!!!
#include<stdio.h>
#include<conio.h>
struct node{
int data;
struct node *link;
}*head = NULL, *new_node, *ptr=NULL, *prev_ptr, *temp;
void insertBeg(){
int info;
new_node = (struct node*)malloc(sizeof(struct node));
printf("\nEnter data : ");
scanf("%d",&info);
new_node->data=info;
new_node->link=NULL;
if(head==NULL){
head=new_node;
}
else{
new_node->link=head;
head=new_node;
}
}
void insertEnd(){
int info;
new_node = (struct node*)malloc(sizeof(struct node));
printf("\nEnter data : ");
scanf("%d",&info);
new_node->data=info;
if(head==NULL){
head=new_node;
new_node->link=NULL;
}
else{
prev_ptr=head;
ptr=head->link;
while(ptr!=NULL){
prev_ptr=ptr;
ptr=ptr->link;
}
prev_ptr->link=new_node;
new_node->link=NULL;
}
}
void displayNode(){
printf("\nLinked List is : ");
ptr=head;
while(ptr!=NULL){
printf("%d--->",ptr->data);
ptr=ptr->link;
}
}
void deleteBeg(){
if(head==NULL){
printf("\nUnderflow");
}
else{
temp=head;
head=head->link;
free(temp);
}
}
void deleteEnd(){
if(head==NULL){
printf("\nUnderflow");
}
else{
prev_ptr=head;
ptr=head->link;
while(ptr!=NULL){
prev_ptr=ptr;
ptr=ptr->link;
}
prev_ptr->link=NULL;
free(ptr);
}
}
void traverse(){
int count=0;
ptr=head;
while(ptr!=NULL){
ptr=ptr->link;
count++;
}
printf("\nNumber of elements in the list are : %d",count);
}
void main(){
int choice,ch='y';
clrscr();
label:
printf("\nPress 1 to insert at beg\n2 to insert at end");
printf("\n3 to delete from beg\n4 to delete from end");
printf("\n5 to display the list\n6 to traverse the linked list : ");
scanf("%d",&choice);
switch(choice){
case 1: insertBeg();
break;
case 2: insertEnd();
break;
case 3: deleteBeg();
break;
case 4: deleteEnd();
break;
case 5: displayNode();
break;
case 6: traverse();
break;
default: printf("\nInvalid Option");
}
printf("\nPress y to continue or any other key to exit : ");
scanf("%s",&ch);
if(ch=='y' || ch=='Y'){
goto label;
}
getch();
}
回答1:
The loop
while(ptr!=NULL){
runs until ptr is NULL, meaning that the later call free(ptr) has no effect.
You could fix this by exiting the loop one iteration sooner instead
void deleteEnd(){
if(head==NULL){
printf("\nUnderflow");
}
else{
prev_ptr=head;
ptr=head;
while(ptr->link!=NULL){
prev_ptr=ptr;
ptr=ptr->link;
}
prev_ptr->link=NULL;
free(ptr);
}
}
You may want to consider extending this with special treatment for the case where the end element is head
来源:https://stackoverflow.com/questions/21364493/menu-driven-program-in-c-to-perform-various-operations-on-a-linked-list