您的位置:首页 > 其它

不带头结点的单链表的插入,删除,原地转置,判断空,清空,统计节点数目等操作

2017-07-19 19:53 459 查看
//不带头结点的单链表
#include<stdio.h>
#include<malloc.h>
//链表结构体
typedef struct _Node
{
int val;
struct _Node* next;
}Node,*LinkList;
void InitList(LinkList* list)
{
*list = NULL;
}
void InsertHeadList(LinkList* list)
{
in
4000
t data;
scanf("%d", &data);
while (data != 0)
{
Node* node = (Node*)malloc(sizeof(Node));
node->val = data;
if (*list == NULL)
{
*list = node;
(*list)->next = NULL;
}
else
{
node->next = *list;
*list = node;
}
scanf("%d", &data);
}
}
void Print(LinkList list)
{
Node* s = list;
while (s != NULL)
{
printf("%d ", s->val);
s = s->next;
}
printf("\n");
}
void InsertTailList(LinkList* list)
{
int data;
scanf("%d", &data);
while (data != 0)
{
Node* node = (Node*)malloc(sizeof(Node));
node->val = data;
node->next = NULL;
if (*list == NULL)
{
*list = node;
}
else
{
Node* s = *list;
while (s->next != NULL)
{
s = s->next;
}
s->next = node;
}
scanf("%d", &data);
}
}
void DeleteHeadList(LinkList* list)
{
if (*list == NULL)
{
return;
}
Node* s = *list;
*list = (*list)->next;
free(s);
}
void DeleteTailList(LinkList* list)
{
if (*list == NULL)
{
return;
}
Node* s = *list;
if (s->next == NULL)
{
DeleteHeadList(list);
}
while (s->next->next != NULL)
{
s = s->next;
}
Node* r = s->next;
s->next = s->next->next;
free(r);
}
int Count(LinkList list)
{
Node* s = list;
int count = 0;
while (s != NULL)
{
s = s->next;
count++;
}
return count;
}
bool IsEmpty(LinkList list)
{
if (list != NULL)
{
return false;
}
return true;
}
void Clear(LinkList* list)
{
while (*list != NULL)
{
DeleteHeadList(list);
}
}
void Reverse(LinkList* list)
{
if (*list == NULL || (*list)->next == NULL)
{
return;
}
//三节点法
Node* first;
Node* second;
Node* last;
first = *list;
second = (*list)->next;
last = second->next;
first->next = NULL;
//如果有三个节点以上开始转置
while (last != NULL)
{
//连接
second->next = first;
//后移
first = second;
second = last;
last = last->next;
}
second->next = first;
*list = second;

}
int main(void)
{
LinkList list;
//初始化
InitList(&list);
//插入
//头插
//InsertHeadList(&list);
//尾插
InsertTailList(&list);
//统计节点个数
int ncount = Count(list);
printf("ncount=%d\n", ncount);
//单链表原地转置
Reverse(&list);
//打印
Print(list);
//删除
//头删
DeleteHeadList(&list);
//尾删
DeleteTailList(&list);
Print(list);
//判断是否为空
bool temp = IsEmpty(list);
if (temp)
{
printf("空\n");
}
else
{
printf("不是空\n");
}
//清空
Clear(&list);
temp = IsEmpty(list);
if (temp)
{
printf("空\n");
}
else
{
printf("不是空\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐