实现单链表的基本运算:初始化、插入、删除、求表的长度、判空、释放。
(1)初始化单链表L,输出L->next的值;
(2)依次采用尾插法插入元素:输入分两行数据,第一行是尾插法需要插入的字符数据的个数,第二行是具体插入的字符数据。
(3)输出单链表L;
(4)输出单链表L的长度;
(5)判断单链表L是否为空;
(6)输出单链表L的第3个元素;
(7)输出元素a的位置;
(8)在第4个元素位置上插入‘x’元素;
(9)输出单链表L;
(10)删除L的第3个元素;
(11)输出单链表L;
(12)释放单链表L。
输入格式:
两行数据,第一行是尾插法需要插入的字符数据的个数,第二行是具体插入的字符数据。
输出格式:
按照题目要求输出
输入样例:
5
a b c d e
输出样例:
0
a b c d e
5
no
c
1
a b c x d e
a b x d e
#include <stdio.h>
#include <malloc.h>
typedef struct LNode
{
char data;
struct LNode *next;
} LNode;
void print(LNode *L)
{
LNode *p=L->next;
while(p->next)
{
printf("%c ",p->data);
p=p->next;
}
printf("%c\n",p->data);
}
void length(LNode *L)
{
LNode *p=L->next;
int i=0;
while(p)
{
i++;
p=p->next;
}
printf("%d\n",i);
}
void Empty(LNode *L)
{
if(L->next)
printf("no\n");
else
printf("yes\n");
}
void problem6(LNode *L)
{
int i=0;
LNode *p=L->next;
while(p)
{
i++;
if(i==3)
{
printf("%c\n",p->data);
break;
}
p=p->next;
}
}
void problem7(LNode *L,char a)
{
int i=0;
LNode *p=L->next;
while(p)
{
i++;
if(p->data==a)
{
printf("%d\n",i);
break;
}
p=p->next;
}
}
void problem8(LNode *L)
{
int i=0;
LNode *p=L->next;
while(p)
{
i++;
if(i==3)
{
LNode *h=(LNode*)malloc(sizeof(LNode)),*n;
h->data='x';
h->next=NULL;
n=p->next;
p->next=h;
h->next=n;
}
p=p->next;
}
}
void problem10(LNode *L)
{
int i=0;
LNode *p=L->next;
while(p)
{
i++;
if(i==2)
{
p->next=p->next->next;
}
p=p->next;
}
}
void problem12(LNode *L)
{
LNode *p=L->next,*del;
while(p)
{
del=p;
p=p->next;
free(del);
}
}
int main()
{
LNode *L = (LNode*)malloc(sizeof(LNode)),*r;
L->data=NULL;
L->next = NULL;
printf("%d\n",L->next);
int n;
scanf("%d ",&n);
for(int i=0; i<n; i++)
{
LNode *p = (LNode*)malloc(sizeof(LNode));
p->next=NULL;
if(i==n-1)
scanf("%c",&p->data);
else
scanf("%c ",&p->data);
if(L->next==NULL)
{
L->next=p;
r=p;
}
else
r->next = p,r=p;
}
print(L);
length(L);
Empty(L);
problem6(L);
problem7(L,'a');
problem8(L);
print(L);
problem10(L);
print(L);
problem12(L);
}