供参考:
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
int id;
char name[16];
int age;
char job;
char title[16];
struct node* next;
}Node,*LinkList;
void create_list(LinkList* L)
{
LinkList pL = NULL, pnew = NULL, ptail = NULL;
(*L) = (LinkList)malloc(sizeof(Node));
(*L)->next = NULL;
pL = (*L);
while (1) {
pnew = (LinkList)malloc(sizeof(Node));
pnew->next = NULL;
scanf("%d", &pnew->id);
if (pnew->id == 0) {
free(pnew);
break;
}
scanf("%s %d %c %s", pnew->name, &pnew->age, &pnew->job, pnew->title);
pL->next = pnew;
pL = pnew;
}
}
void print_list(LinkList L)
{
LinkList pL = L;
if (!L || !L->next) return;
printf("编号\t姓名\t年龄\t职业\t班级/职称\n");
while (pL->next) {
printf("%d\t%s\t%d\t%c\t%s\n", pL->next->id,
pL->next->name, pL->next->age, pL->next->job, pL->next->title);
pL = pL->next;
}
}
void print_node(Node* p)
{
Node* pL = p;
if (!pL ) return;
printf("编号\t姓名\t年龄\t职业\t班级/职称\n");
printf("%d\t%s\t%d\t%c\t%s\n", pL->id,
pL->name, pL->age, pL->job, pL->title);
}
Node* find_agemax(LinkList L)//返回年龄最大结点的前置结点
{
Node* p = NULL,*pmax=NULL;
int age_max = -1;
for (p = L; p->next; p = p->next) {
if (p->next->age > age_max) {
age_max = p->next->age;
pmax = p;
}
}
if (pmax)
print_node(pmax->next);//年龄最大的结点数据输出
return pmax;
}
void insert_Node(LinkList L, Node* pt, int i)//将 pt 结点插入编号值 i 之后
{
if (!L || !L->next) return;
LinkList pL = L;
while (pL->next && pL->next->id <= i)
pL = pL->next;
pt->next = pL->next;
pL->next = pt;
}
void delete_Node(Node* p) //删除结点 p->next
{
Node* pre = p;
p = p->next;
if (!p) return;
pre->next = p->next;
free(p);
}
int main()
{
LinkList L = NULL, pf = NULL, pt = (Node*)malloc(sizeof(Node));
pt->next = NULL;
create_list(&L);//建立一个带有头结点的动态链表(长度取决于输入的个数,当输入编号为0时结束)
print_list(L); //输出链表中所有结点的数据。
pf = find_agemax(L);//在链表中查找年龄最大的结点并输出对应的数据
pt->age = pf->next->age;
pt->job = pf->next->job;
pt->id = pf->next->id;
strcpy(pt->name, pf->next->name);
strcpy(pt->title, pf->next->title);
delete_Node(pf); //将链表中将最大年龄的结点删除。
print_list(L);
insert_Node(L, pt, 1); //在链表中把3)中删除的节点再插入到编号1和2之间。
print_list(L);
return 0;
}