# 数据结构常用函数（一）

#include <stdlib.h>

typedef struct
{
char key[15];
char name[20];
int age;
}DATA;

typedef struct Node{
DATA data;
struct Node *next;
}ChainListType;

void ChainlistPrintAll(ChainListType *head); 

1.遍历链表

void ChainlistPrintAll(ChainListType *head)
{
ChainListType *h;
DATA data;
printf("list as fllowing:\n");
while(h){//处理每一个节点
data=h->data;
printf("(%s,%s,%d)\n",data.key,data.name,data.age);
h=h->next;//准备处理下一个节点
}
return ;
}

2.链表元素个数

int ChainListLength(ChainListType *head)
{
ChainListType *h;
int i=0;
while(h){
i++;
h=h->next;//遍历计数
}
return i;
}

3.删除某个节点

int ChainListDelete(ChainListType *head,char *key)
{
ChainListType *node,*h;
while(h){
if(strcmp(h->data.key,key)==0){//找关键字
node->next=h->next;
free(h);//释放内存
return 1;
}else{
node=h;
h=h->next;//没找到就接着找
}
}
return 0;
}

4.插入某个元素

ChainListType *ChainListInsert(ChainListType *head,char *findkey,DATA data)
{
ChainListType *node,*node1;
if(!(node=(ChainListType *)malloc(sizeof(ChainListType))))
{
printf("node's application fail!\n");
return 0;
}
node->data=data;
if(node1){
node->next=node1->next;
node1->next=node;
}else{
free(node);
printf("do not find the place!\n");
}
}

5.查找某个元素

ChainListType *ChainListFind(ChainListType *head,char *key)
{
ChainListType *h;
while(h){//节点有效
if(strcmp(h->data.key,key)==0)
return h;
h=h->next;
}
return NULL;
}

6.添加头节点

ChainListType *ChainListAddFirst(ChainListType *head,DATA data)
{
ChainListType *node,*h;
if(!(node=(ChainListType *)malloc(sizeof(ChainListType))))
{
printf("node's application fail!\n");
return NULL;
}
node->data=data;
}

7.添加尾节点

ChainListType *ChainListAddEnd(ChainListType *head,DATA data)
{
ChainListType *node,*h;
if(!(node=(ChainListType *)malloc(sizeof(ChainListType))))
{
printf("node's application fail!\n");
return NULL;
}
node->data=data;
node->next=NULL;
}
while(h->next!=NULL)
h=h->next;
h-next=node;
}

#include <iostream>
#include <string.h>
#include "ChainList_API.h"

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv)
{
DATA data;
char key[15],findkey[15];

printf("Enter the data in the linked list, including keywords, names, age：\n");

do{
fflush(stdin);
scanf("%s",data.key);
if(strcmp(data.key,"0")==0) break;
scanf("%%d",data.name,data.age);
}while(1);

printf("\nEnter the insertion node's keyword:\n");
scanf("%s",&findkey);
printf("Enter the data in the linked list, including keywords, names, age：\n");
scanf("%s%s%d",data.key,data.name,data.age);

printf("Enter search keywords:\n");
fflush(stdin);
scanf("%s",key);
if(node){
data=node->data;
printf("The keyword %s corresponding node is:(%s,%s,%d)",key,data.key,data.name,data.age);
}else
printf("No corresponding node found!\n");

printf("Enter keywords to delete:\n");
fflush(stdin);
scanf("%s",key);

return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120