2
下面的代碼工作正常,除了deleteEnd功能的所有功能進行各種操作。當我執行程序時,所有的函數都執行它們應該執行的任務,但是deleteEnd函數什麼也不做。鏈接列表在執行deleteEnd函數時沒有變化。請幫忙!!!!菜單在C驅動程序鏈表
#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();
}
請正確縮進代碼。而且幾條空白線也不會太差。 – Nabla