C实现头插法和尾插法来构建单链表(不带头结点)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C实现头插法和尾插法来构建单链表(不带头结点)链表的构建事实上也就是不断插⼊节点的过程。

⽽节点的插⼊能够分为头插法和尾插法。

//
// main.c
// HeadInsertAndTailInsert
//
// Created by chenyufeng on 16/2/25.
// Copyright © 2016年 chenyufengweb. All rights reserved.
//
/**
* 分别使⽤头插法和尾插法建⽴单链表
*/
#include <stdio.h>
#include "stdlib.h"
#include "string.h"
typedef int elemType;
//构造节点
typedef struct ListNode{
int element;
struct ListNode *next;
}Node;
//初始化链表
void initList(Node *pNode){
pNode = NULL;
printf("%s函数运⾏,头结点初始化完毕\n",__FUNCTION__);
}
//打印链表
void printList(Node *pNode){
if (pNode == NULL) {
printf("%s函数运⾏,链表为空,打印失败\n",__FUNCTION__);
}else{
while (pNode != NULL) {
printf("%d ",pNode->element);
pNode = pNode->next;
}
printf("\n");
}
}
//头插法
Node *HeadInsert(Node *pNode){
Node *pInsert;
pInsert = (Node*)malloc(sizeof(Node));
if (pInsert == NULL) {
printf("%s函数运⾏。

内存分配失败,建⽴链表失败\n",__FUNCTION__);
return NULL;
}
memset(pInsert, 0, sizeof(Node));
scanf("%d",&(pInsert->element));
pInsert->next = NULL;
if (pInsert->element <= 0) {
printf("%s函数运⾏。

输⼊数据有误,建⽴链表失败\n",__FUNCTION__);
return NULL;
}
while (pInsert->element > 0) {
if (pNode == NULL) {
pNode = pInsert;
}else{
//注意以下语句的顺序,否则可能造成链断裂
pInsert->next = pNode;
pNode = pInsert;
}
pInsert = (Node*)malloc(sizeof(Node));
if (pInsert == NULL) {
printf("%s函数运⾏,内存分配失败,建⽴链表失败\n",__FUNCTION__);
return NULL;
}
memset(pInsert, 0, sizeof(Node));
scanf("%d",&(pInsert->element));
pInsert->next = NULL;
}
printf("%s函数运⾏。

头插法建⽴链表成功\n",__FUNCTION__);
return pNode;
}
//尾插法
Node *TailInsert(Node *pNode){
Node *pInsert; //要插⼊的节点
Node *pMove; //遍历链表的节点
pInsert = (Node*)malloc(sizeof(Node));
if (pInsert == NULL) {
printf("%s函数运⾏,内存分配失败,建⽴链表失败\n",__FUNCTION__); return NULL;
}
memset(pInsert, 0, sizeof(Node));
scanf("%d",&(pInsert->element));
pInsert->next = NULL;
if (pInsert->element <= 0) {
printf("%s函数运⾏。

输⼊数据有误,建⽴链表失败\n",__FUNCTION__); return NULL;
}
pMove = pNode;
while (pInsert->element > 0) {
if (pNode == NULL) {
//注意不要忘了改动pMove指针的指向,初始pMove⼀定要指向头节点 pNode = pInsert;
pMove = pNode;
}else{
//遍历找到最后⼀个节点
while (pMove->next != NULL) {
pMove = pMove->next;
}
pMove->next = pInsert;
}
pInsert = (Node*)malloc(sizeof(Node));
if (pInsert == NULL) {
printf("%s函数运⾏。

内存分配失败,建⽴链表失败\n",__FUNCTION__); return NULL;
}
memset(pInsert, 0, sizeof(Node));
scanf("%d",&(pInsert->element));
pInsert->next = NULL;
}
printf("%s函数运⾏,尾插法建⽴链表成功\n",__FUNCTION__);
return pNode;
}
int main(int argc, const char * argv[]) {
Node *pList;
initList(pList);
printList(pList);
//头插法建⽴链表
pList = HeadInsert(pList);
printList(pList);
//尾插法建⽴链表
pList = TailInsert(pList);
printList(pList);
return 0;
}。

相关文档
最新文档