线性表的初始化,头部和尾部插入,删除C/C++代码实现

// List.cpp : 定义控制台应用程序的入口点。
//visual studio 2013


#include "stdafx.h"
#include"iostream"
#include "string.h"
#define LEN 10
using namespace std;


//定义结构体
struct ListNode
{
int data;
ListNode* next;
};
//定义ListNode指针型的ListLink
typedef ListNode* ListLink;
//初始化线性表
void InitList(ListLink &List)
{
List = (ListLink)malloc(sizeof(ListNode));
if (List)
{
List->next = NULL;
cout << "初始化sucess" << endl;
}

else
{
cout << "Error InitList" << endl;

}
//删除线性表
int DeleteList(ListLink &List)
{
ListNode* q = (ListNode*)malloc(sizeof(ListNode));
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
p = List->next;
while (p)
{
q = p->next;
free(p);
p = q;
}
List->next = NULL;
return 1;
}
//线性表头部插入元素
int InsertHeadList(ListLink &List, int data)
{
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
if (!p)
{
exit(OVERFLOW);
}
p->data = data;
p->next = NULL;
if (List->next == NULL)
{
List->next = p;
}
else{
p->next = List->next;
List->next = p;
}
return 0;
}
//线性表尾部插入元素
int InsertTailList(ListLink &List, int data)
{
//遍历O(n),插入O(1)
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
ListNode* q = (ListNode*)malloc(sizeof(ListNode));
q->data = data;
q->next = NULL;
p = List;
while (p->next)
{
p = p->next;
}
p->next = q;
return 0;
}
//在第i个元素之前插入元素
int InsertList(ListLink &List, int insertLocation, int data)
{
int count = 0;
int listLength = 0;
ListNode* p = (ListNode*)malloc(sizeof(ListNode));
ListNode* q = (ListNode*)malloc(sizeof(ListNode));
 
q->data = data;
q->next = NULL;
p = List->next;
while (p->next)
{
p = p->next;
listLength++;
}
if (insertLocation > listLength&&insertLocation < 0)
{
cout << "插入的位置不合法" << endl;
return 0;
}
if (insertLocation == 1)
{
q->next = List;
List = q;
}
p = List;
while (--insertLocation)
{
p = p->next;
}


q->next = p->next;
p->next = q;
p = List;
while (p->next)
{
count++;
 
p = p->next;

}
cout << "List表中的元素个数:" << endl;
cout << count << endl;
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
ListLink L;
InitList(L);
for (int i = 0; i < LEN; i++)
{
InsertHeadList(L, i);
InsertTailList(L, i);
}
ListNode* q = (ListNode*)malloc(sizeof(ListNode));
q = L->next;

InsertList(L,3,123);
cout << "遍历List:" << endl;
while (q)
{
cout << q->data << endl;
q = q->next;
}
if (DeleteList(L))
cout << "删除成功" << endl;
if (L->next == NULL)
{
cout << "kong" << endl; 
}
delete L;

system("pause");
return 0;
}


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值