插入值没有插在头节点之前的,注意删除值的时候可能会删掉头节点。
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int num;
struct node* next;
}Node;
Node *createnode(int num);
void addnode(int num1,int num2,Node *head);
Node *deletenode(int num,Node *head);
void printlist(Node *head);
void myfunc(int index,int headnum);
int main(void)
{
int index,headnum;
while(scanf("%d %d",&index,&headnum) == 2){
myfunc(index,headnum);
}
return 0;
}
Node *createnode(int num)
{
Node *pt;
pt = (Node*)malloc(sizeof(Node));
pt->num = num;
pt->next = NULL;
return pt;
}
void addnode(int num1,int num2,Node *head)
{
Node *now,*add;
now = head;
while(now->num != num2) now = now->next; //找到num2
add = createnode(num1);
add->next = now->next;
now->next = add;
}
Node *deletenode(int num,Node *head)
{
Node *now,*pre;
now = head,pre = head;
while(now->num != num){
pre = now;
now = now->next; //找到num
}
if(now == head){
head = head->next; //如果删除的是头部节点
}else{
pre->next = now->next;
}
free(now);
return head; //删除节点有可能改变头节点的位置,所以要返回头节点
}
void printlist(Node *head)
{
Node * now;
for(now = head;head != NULL;head = now){
printf("%d ",head->num);
now = head->next;
free(head);
}
printf("\n");
}
void myfunc(int index,int headnum)
{
int num,add;
int i;
Node *head = createnode(headnum);
for(i=0;i<index-1;i++){
scanf("%d %d",&add,&num);
addnode(add, num, head);
}
scanf("%d",&num);
head = deletenode(num,head);
printlist(head);
}



京公网安备 11010502036488号