赞
踩
- #include<iostream>
- #define ElemType int
- using namespace std;
-
- typedef struct Node {
- ElemType data;
- struct Node *next;
- };
-
- void Create(Node *&l) { //尾插法
- int x;
- l->next = NULL; //头结点
- Node *s,*r = l; //r为表尾指针
- cin >> x;
- while (x != -1) {
- s = new Node;
- s->data = x;
- r->next = s;
- r = s;
- cin >> x;
- }
- r->next = NULL;
- }
-
- void Print(Node *&l) { //输出链表中的数据
- Node *p = l->next;
- while (p != NULL) {
- cout << p->data << " ";
- p = p->next;
- }
- cout << endl;
- }
-
- void Delete(Node *&l) { //单链表的删除操作
- Node *p = l;
- Node *q = l->next; //保存后继指针,防止断链
-
- while (p!= NULL ) {
- delete p;
- p = q;
- if (q != NULL) {
- q = q->next;
- }
- }
- }
-
- void Sort(Node *&l) { //采用头插法
- Node *p = l->next, *pre;
- Node *r = p->next;
- p->next = NULL;
- p = r;
- while (p!=NULL) {
- r = p->next;
- pre = l;
- while (pre->next != NULL&&pre->next->data < p->data) {
- pre = pre->next;
- }
- p->next = pre->next;
- pre->next = p;
- p = r;
- }
-
- }
- int main() {
- Node *l = new Node; //新建结点,并且创建指针
- Create(l);
- Print(l);
- Sort(l);
- Print(l);
- Delete(l); //释放内存
- system("pause");
- return 0;
- }
-
- /*
- 12 43 56 67 34 32 12 65 -1
- */
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。