- 创建单向链表
- 输出链表
- 输出尾节点的值
- 输出节点个数
- 输出奇数节点的个数
- 求最大值
- 逆向输出链表
本链表以储存一整型数据为例,用C语言实现
#include <stdio.h>
#include <stdlib.h>
#define N 5
typedef struct node {
int date;
struct node * next;
}ElemSN;
//创建单向链表
ElemSN * CreateLink(int a[])
{
ElemSN * h, *tail, *p;
int i = 1;
h=tail= (ElemSN *)malloc(sizeof(ElemSN));
h->date = a[0];
h->next = NULL;
for (i; i < N; i++)
{
p = (ElemSN *)malloc(sizeof(ElemSN));
p->date = a[i];
p->next = NULL;
tail->next = p;
tail = p;
}
return h;
}
//输出单向链表
void PrintLink(ElemSN * h)
{
ElemSN * p;
for (p = h; p != NULL; p = p->next)
{
printf("%d\t", p->date);
}
}
//输出尾节点的值
ElemSN * TailNode(ElemSN * h)
{
ElemSN * p;
for (p = h; p->next; )
p = p->next;
return p;
}
//输出节点个数
int CountNode(ElemSN * h)
{
int count = 0;
ElemSN * p;
for (p = h; p; p = p->next)
count++;
return count;
}
//输出奇节点的个数
int CountoddNode(ElemSN * h)
{
int odd = 0;
ElemSN * p;
for (p = h; p; p = p->next)
odd += p->date % 2;
return odd;
}
//输出最大值
ElemSN * MaxNode(ElemSN *h)
{
ElemSN *Pmax, *p;
Pmax = h;
for (p = h->next; p; p = p->next)
if (Pmax->date < p->date)
Pmax = p;
return Pmax;
}
//逆向输出链表
void PriePrintLink(ElemSN *h)
{
ElemSN *pend = NULL, *p;
while (pend-h)
{
for (p = h; p->next - pend; p = p->next);
printf("%d\t", p->date);
pend = p;
}
}
int main()
{
int a[5] = { 18,9,78,36,45 };
ElemSN * head, *Pmax, *Ptail;
int count, countodd;
//创建单向链表
head = CreateLink(a);
//输出单向链表
PrintLink(head);
printf("\n");
//输出尾节点的值
Ptail = TailNode(head);
printf("尾节点的值为%d\n", Ptail->date);
//输出节点个数
count = CountNode(head);
printf("节点个数为%d\n",count);
//输出奇节点的个数
countodd = CountoddNode(head);
printf("奇节点个数为%d\n", countodd);
//输出最大值
Pmax = MaxNode(head);
printf("最大值为%d\n", Pmax->date);
//逆向输出链表
PriePrintLink(head);
printf("\n");
return 0;
}