链表操作

来源:互联网 发布:plc编程证书 编辑:程序博客网 时间:2024/06/05 14:53
/*************************************************************/#include<stdio.h>#include<stdlib.h>/*************************************************************/struct Node{int data;struct Node *next;};struct List{int length;struct Node *head;};/**************************************************************/struct List *List_Construct(void);char List_Empty(struct List *pList);char List_Insert(struct List *pList,int a);char List_Traverse(struct List *pList);struct Node* List_Search(struct List *pList ,int a);char List_DropElement(struct List *pList,int ele);char List_Sort(struct List *pList);/**************************************************************/int main(){struct List *pList=List_Construct();if(List_Empty(pList))printf("The List is empty\n");List_Insert(pList,1);List_Insert(pList,3);List_Insert(pList,6);List_Insert(pList,5);List_Insert(pList,7);List_Traverse(pList);List_Sort(pList);List_Traverse(pList);List_DropElement(pList,7);List_Traverse(pList);printf("The length of the List is%d\n",pList->length);return 1;}/**************************************************************/struct List *List_Construct(void){//建表struct List *pList=(struct List*)malloc(sizeof(struct List));//头节点pList->head=(struct Node*)malloc(sizeof(struct Node));pList->head->next=NULL;pList->length=0;return pList;}char List_Empty(struct List *pList){//如果空,返回1if(pList->head->next==NULL)return 1;return 0;}char List_Insert(struct List *pList,int a){struct Node *NewNode=(struct Node*)malloc(sizeof(struct Node));//插在表头位置NewNode->next=pList->head->next;NewNode->data=a;pList->head->next=NewNode;pList->length++;return 1;}char List_Traverse(struct List *pList){if(List_Empty(pList)){printf("Sorry,but the Listlist is empty.");return 0;}else{struct Node *pNode=pList->head->next;while(pNode!=NULL){printf("%6d",pNode->data);pNode=pNode->next;}printf("\n");return 1;}}struct Node* List_Search(struct List *pList,int a){struct Node *frontnode=pList->head;struct Node *pNode=pList->head->next;while(pNode!=NULL){if(pNode->data==a){//为便于删除操作,返回查找元素的前一个节点return frontnode;}frontnode=pNode;pNode=pNode->next;}return NULL;}char List_DropElement(struct List *pList,int ele){struct Node *temp=NULL;struct Node *pNode=List_Search(pList,ele);if(List_Empty(pList)){printf("Sorry,but the List is empty.");return 0;}if(pNode==NULL){printf("The element %d is not found",ele);return 0;}else{temp=pNode->next;pNode->next=temp->next;free(temp);pList->length--;return 1;}}char List_Sort(struct List *pList){struct Node *pNode=pList->head->next;struct Node *qNode=pNode;struct Node *little_node=pNode;int temp;while(pNode!=NULL){while(qNode!=NULL){if(qNode->data<little_node->data){little_node=qNode;}qNode=qNode->next;}temp=little_node->data;little_node->data=pNode->data;pNode->data=temp;pNode=pNode->next;qNode=pNode;little_node=pNode;}return 1;}

原创粉丝点击