试题描述
先将键盘输入的一组整数依次存入循环链表(头插法),然后删除最末尾元素,最后将其余元素正序输出。
样例输入
3 1 7 5 9
样例输出
1 5 7 9
语言
C
OJ提交结果
KLP平台编译运行通过,答案正确。
思路分析
根据题目意思要求使用头插法建立单链表,并且删除最末尾元素,所以本题在初始化建立单链表的时候做了一些手脚,直接对第一个读入的整数不作任何处理,从第二个整数开始构建单链表(头插法)。
套用头插法建立带头结点的单链表模板
//头插法建立带头结点的单链表
LinkList CreateFromHead()
{
LinkList L;
Node *s;
int flag = 1;
L = (LinkList)malloc(sizeof(Node));
L->next = NULL;
while(flag)
{
char c = getchar();
if(c != '$')
{
s = (Node *)malloc(sizeof(Node));
s->data = c;
s->next = L->next;
L->next = s;
}
else
{
flag = 0;
}
}
return L;
}
为防止时间超限,本题采用判断读入每一个整数后一位字符的方式,如果!= EOF,则继续读入,反之则退出循环,完成单链表的构建。
要求正序输出,套用对一个带头结点的单链表进行冒泡排序模板
void Bubble(LinkList L)
{
int i ,count = 0, num;
Node *p, *q, *tail;
p = L;
while(p->next != NULL)
{
count++;
p = p->next;
}
for(i = 0; i < count - 1; i++)
{
num = count - i - 1;
q = L->next;
p = q->next;
tail = L;
while(num--)
{
if(q->data > p->data)
{
q->next = p->next;
p->next = q;
tail->next = p;
}
tail = tail->next;
q = tail->next;
p = q->next;
}
}
}
源代码
#include<stdio.h>
#include<malloc.h>
typedef struct Node{
int data;
struct Node *next;
}Node, *LinkList;
LinkList CreateFromHead()
{
LinkList L;
L = (Node *)malloc(sizeof(Node));
Node *s = NULL;
char ch = 0;
int n;
int x;
L->next = NULL;
scanf("%d",&x);
while ( ch != EOF)
{
scanf("%d",&n);
s = (Node *)malloc(sizeof(Node));
s->data = n;
s->next = L->next;
L->next = s;
ch = getchar();
}
return L;
}
void Bubble(LinkList L)
{
int i ,count = 0, num;
Node *p, *q, *tail;
p = L;
while(p->next != NULL)
{
count++;
p = p->next;
}
for(i = 0; i < count - 1; i++)
{
num = count - i - 1;
q = L->next;
p = q->next;
tail = L;
while(num--)
{
if(q->data > p->data)
{
q->next = p->next;
p->next = q;
tail->next = p;
}
tail = tail->next;
q = tail->next;
p = q->next;
}
}
}
void Print(LinkList L)
{
Node *p;
p = L->next;
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
}
int main()
{
LinkList L1 = CreateFromHead();
Bubble(L1);
Print(L1);
return 0;
}