加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c/c++实现链表的各个函数和调用

发布时间:2020-12-15 04:58:14 所属栏目:百科 来源:网络整理
导读:#include using namespace std; typedef struct _Node { int value; struct _Node *next; }Node; typedef struct _list { Node *head; }List; void _add(List *plist,int num); void print(List *list); bool search(List *plist,int num); void ldelete(Lis

#include

using namespace std;

typedef struct _Node {

int value;

struct _Node *next;

}Node;

typedef struct _list {

Node *head;

}List;

void _add(List *plist,int num);

void print(List *list);

bool search(List *plist,int num);

void ldelete(List *plist,int num);

void freeall(List *list);

bool insert(List *plist,int position,int num);

int main()

{

int num,in,pos;

List list;

list.head = NULL;

do

{

cin >> num;

if(num!=-1)

_add(&list,num);

}

while (num != -1);

print(&list);

cout << "请输入你要查找的数字=>";

cin >> in;

if (search(&list,in))

cout << "找到了" << endl;

else

cout << "没找到" << endl;

cout << "请输入你要删除的数字=>";

cin >> in;

ldelete(&list,in);

print(&list);

cout << "请输入你要插入的位置和元素=>";

cin >> pos >> in;

insert(&list,pos,in);

print(&list);

freeall(&list);

return 0;

}

void _add(List *plist,int num)//新建链表

{

Node *p = (Node*)malloc(sizeof(Node));

p->value = num;

p->next = NULL;

if (plist->head)

{

Node *last = plist->head;

for (; last->next; last = last->next);

//while (last->next)

// last = last->next;

last->next = p;

}

else

plist->head = p;

}

void print(List *list)//打印链表

{

Node *p;

for (p = list->head; p; p = p->next)

cout <value;

cout << endl;

}

bool search(List *plist,int num)//搜索

{

Node *p;

for (p = plist->head; p; p = p->next)

if (p->value == num)

return 1;

return 0;

}

void ldelete(List *plist,int num)//删除指定结点

{

Node *p,*q=NULL;

for (p = plist->head; p; q=p,p = p->next)

if (p->value == num)

{

if (q)

q->next = p->next;

else

plist->head = p->next;

free(p);

break;

}

}

void freeall(List *list)//删除链表

{

Node *p,*q;

for (p = list->head; p; p = q)

{

q = p->next;

free(p);

}

}

bool insert(List *plist,int num)

{

int cnt = 1;

Node *p,*q;

Node *m = (Node *)malloc(sizeof(Node));

m->value = num;

m->next = NULL;

for (p = plist->head,q=NULL; p; q=p,p = p->next)

{

if (cnt == position)

{

if (q)

{

q->next = m;

m->next = p;

}

else

{

m->next = plist->head;

plist->head = m;

}

return 1;

}

cnt++;

}

return 0;

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读