C/C++ 知识回顾 单链表基本操作
2017-02-28 14:49
375 查看
#include<iostream> #include<vector> #include<algorithm> #include<cstdio> using namespace std; typedef struct student { int data; struct student * next; } node; //链表的创建 void create(node ** head) { *head = (node *)malloc(sizeof(node)); node *p=*head, *q; int x; while (true) { cin >> x; if (x) { q = (node *)malloc(sizeof(node)); q->next = NULL; q->data = x; p->next = q; p = q; } else { break; } } *head = (*head)->next;//注意!!! } //链表的长度计算 int length(node * head) { if (head==NULL) { return 0; } int n = 0; node *p = head; while (p) { n++; cout << n << ":" << p->data << endl; p = p->next; } return n; } //删除链表中某值 void delet(node * head, int n) { if (!head) { cout << "链表为空" << endl;; return; } node *p = head; node *q = head; while (p) { if (p->data==n) { if (p==head) { head = p->next; free(p); } else { q->next = p->next; free(p); } } q = p; p = q->next; } } //单链表打印 void print(node *head) { if (!head) { cout << "链表为空" << endl;; return; } node *p = head; while (p) { cout << p->data << endl; p = p->next; } } //单链表插入 node * insert(node* head, int n) { node *p0, *p1, *p2=NULL; p1 = head; p0 = (node *)malloc(sizeof(node)); p0->data = n; while (p0->data > p1->data&&p1->next != NULL) { p2 = p1; p1 = p1->next; } if (p0->data<=p1->data) { if (head==p1) { p0->next = p1; head = p0; } else { p2->next = p0; p0->next = p1; } } else { p1->next = p0; p0->next = NULL; } return head; } //单链表排序 node * sort(node *head) { if (!head||!head->next) { return head; } node * p = head->next; node *pre = head; while (pre->next) { p = pre->next; while (p) { if (pre->data<=p->data) { p = p->next; continue; } int temp = pre->data; pre->data = p->data; p->data = temp; p = p->next; } pre = pre->next; } return head; } //单链表倒置 node *reverse(node * head) { if (!head||!head->next) { return head; } node *p1 = head, *p2 = head->next,*p3=p2; while (p2) { p3 = p2->next; p2->next = p1; p1 = p2; p2 = p3; } head->next = NULL; return p1; } //寻找中间结点 node * searchmid(node *head) { node *temp = head; while (head->next&&head->next->next) { head = head->next->next; temp = temp->next; } return temp; } int main() { node * head=NULL; create(&head); head = sort(head); print(head); return 0; }
相关文章推荐
- C++写的模板类链表基本操作
- C++中单链表的建立与基本操作
- C++实现链表基本操作
- Day 4:C++基本语法知识回顾复习
- C++模拟双向链表的基本操作
- 详细的单链表基本操作C/C++实现
- C++数据结构 链表的基本操作
- C++实现链表的基本操作及测试用例
- 【C++/数据结构】循环链表的基本操作
- 使用C++链表来实现二叉树的存储和基本操作
- c++链表基本操作
- C++-----单链表基本操作
- C++ 双链表的基本操作
- 实例讲解C++ 双链表基本操作
- 通过例子回顾C++基本知识(一)
- [C++]数据结构:有序链表SortedChain的基本实现与操作
- 单链表结点读取、插入、删除操作(基本操作)-C++
- c++实现链表的基本操作
- c++之链表篇1:单向链表的创建,打印,删除,插入,销毁等基本操作
- 链表的基本操作C/c++