单向链表的创建,插入,删除,排序,查找---新人贴

来源:互联网 发布:第九届杭州网络文化节 编辑:程序博客网 时间:2024/06/07 00:31
#include<iostream>using namespace std;typedef  int ValType;typedef struct Node{ValType val;struct Node * next;}Node;void ListNodeCreat(Node *&Star,int n){Node* New ;Star = (Node *)malloc(sizeof(Node*));Star->val = 0;Star->next = NULL;ValType NewVal=0;cout << "Now,Input the Val of ListNode!" << endl;for (int i =0; i <n ;i++){New = (Node*)malloc(sizeof(Node*));cin >> New->val;New->next = Star->next;Star->next = New;}}int LangTest(struct Node *ListNode){Node *Tmp;Tmp = (Node* )malloc(sizeof(Node*));int cnt = 0;Tmp = ListNode;while (Tmp != NULL){Tmp = Tmp->next;cnt++;}cnt--;return cnt;}void Display(struct Node *ListNode){Node* tmp;tmp = (Node*)malloc(sizeof(Node*));tmp = ListNode->next;cout << "The ListNode:" ;while (tmp != NULL){cout << tmp->val << "->";tmp = tmp->next;}cout << endl;}void InsertListNode(struct Node *ListNode,int val,int num){Node* tmp;tmp = (Node*)malloc(sizeof(Node*));tmp=ListNode->next;int cnt = 1;while (tmp != NULL){if (cnt == num-1){Node *New;New = (Node*)malloc(sizeof(Node*));New->val = val;New->next = tmp->next;tmp->next = New;break;}cnt++;tmp = tmp->next;}if (tmp == NULL)cout <<"The ListNode is too short!"<< endl;}void RemoveListNode(struct Node *ListNode, int num){Node* tmp;tmp = (Node*)malloc(sizeof(Node*));tmp = ListNode->next;int cnt = 1;while (tmp != NULL){if (cnt == num-1){tmp->next = tmp->next->next;break;}cnt++;tmp = tmp->next;}if (tmp == NULL)cout << "The ListNode is too short!" << endl;}void SortListNode(struct Node *ListNode){Node *tmp;ValType val_tmp = 0;tmp = (Node*)malloc(sizeof(Node*));int lang = LangTest(ListNode);int i = 0;int j = 0;for (i = 0; i < lang - 1; i++){tmp = ListNode->next;for (j = 0; j < lang - 1 - i; j++){if ((tmp->val)>(tmp->next->val)){val_tmp = tmp->val;tmp->val = tmp->next->val;tmp->next->val = val_tmp;}tmp = tmp->next;}}}void FindListNode(struct Node *ListNode,int num){Node* tmp;tmp = (Node*)malloc(sizeof(Node*));tmp = ListNode->next;int cnt = 1;while (tmp != NULL){if (cnt == num - 1){cout << "The position "<<num<<" is:"<<tmp->val << endl;break;}cnt++;tmp = tmp->next;}if (tmp == NULL)cout << "The ListNode is too short!" << endl;}int main(){printf("Input:How long the ListNode!\n");int lang = 0;cin >> lang;Node *l1,*l2;l1 = (Node*)malloc(sizeof(Node*));l2 = (Node*)malloc(sizeof(Node*));ListNodeCreat(l1,lang);cout << "Creat:" << endl;Display(l1);InsertListNode(l1, 10, 4);cout << "Insert:" << endl;Display(l1);RemoveListNode(l1,3);cout << "Remove:" << endl;Display(l1);SortListNode(l1);cout << "Sort:" << endl;Display(l1);FindListNode(l1, 4);while (1);return 0;}

0 0
原创粉丝点击