[心得] : 1.注意反轉.與delete
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char input_name[255];
int input_age;
struct Node{
char name[255];
int age;
struct Node *next;
};
struct Node *first=NULL;
struct Node *temp=NULL;
struct Node *current=NULL;
void EnterData()
{
printf("please input name :");
scanf("%s",&input_name);
printf("please input age :");
scanf("%d",&input_age);
}
void CreateFirstNode(int input_age,char* input_name)
{
first = (struct Node *)malloc(sizeof(struct Node));
strcpy(first->name,input_name);
first->age =input_age;
current =first;
current->next =NULL;
}
void InsertNode(int input_age,char *input_name)
{
temp=(struct Node*)malloc(sizeof(struct Node));
temp->age =input_age;
strcpy(temp->name,input_name);
temp->next =NULL;
current->next =temp;
current =temp;
}
void deleteNode(char* input_name)
{
struct Node *temp_prev=NULL;
temp =first;
if(temp ==NULL)
printf("NO data to delete");
while(temp!=NULL)
{
if(strcmp(first->name,input_name)==0)
{
first = temp->next;
free(temp);
}
if(strcmp(temp->name,input_name)==0)
{
temp_prev->next =temp->next; //要先把欲刪除的Node_B(temp)的前一個Node_A(temp_prev-)指到B的後面一個Node_C(temp->next)
free(temp);
}
temp_prev=temp;//這兩行指再繼續下一個點
temp=temp->next;
}
}
void display()
{
temp =first;
if(first==NULL)
printf("NO data");
else
{
while(temp!=NULL)
{
printf("name = %s, age = %d \n",temp->name,temp->age);
temp =temp->next;
}
}
}
void Invert_linklist()
{
struct Node *p=NULL;
p=first;
temp=NULL;
while(first->next != NULL)
{
first = p->next; //先把first assign到下一個點
p->next = temp; //p再指回去前面的點
temp=p; //再繼續反轉下一個點
p=first;
}
p->next =temp; //這行很重要,要記得最後要再把p下一個點,指到temp
}
void selsectFun()
{
int i;
printf("------------------------------------\n");
printf("|1 Add Node\n");
printf("|2 Delete Node\n");
printf("|3 Display List Node\n");
printf("|4 Display and Invert List Node\n");
printf("|-1 Exit\n");
printf("------------------------------------\n");
do
{
printf("Enter the function number>");
scanf("%d",&i);
if(i == 1)
{
if(first == NULL)
{
EnterData();
CreateFirstNode(input_age,input_name);
}
else
{
EnterData();
InsertNode(input_age,input_name);
}
}
else if(i == 2)
{
printf("Enter the person's name>");
scanf("%s",&input_name);
deleteNode(input_name);
}
else if(i == 3)
display();
else if(i == 4) {
Invert_linklist();
display();
}
else if(i == -1)
{}
else
printf("Wrong function number!!\n");
}while(i != -1);
}
int main()
{
selsectFun();
system("pause");
return 0;
}
沒有留言:
張貼留言