C# · 12月 19, 2021

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

#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 <<setw(4) <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;

}