1: /* 链表的排序
2: * 题目:无序链表改为从小到大有序
3: */
4:  
5: #include <iostream>
6: #include "stdlib.h"
7: #include "time.h"
8: #define MAXN 10
9: using namespace std;
10:  
11: typedef struct node
12: {
13: int data;
14: struct node *next;
15: }*Link;
16:  
17: //生成一个有十个节点,头结点数值域为空,其余节点为0到9之间
18: // 随机数的单向链表
19: Link createlist()
20: {
21: Link head = (Link)malloc(sizeof(struct node));
22: if (!head)
23: {
24: cout << "memory allocation error!" << endl;
25: exit(0);
26: }
27: Link q = head;
28: srand((unsigned)time(NULL));
29: for (int i=0; i<MAXN; i++)
30: {
31: Link p = (Link)malloc(sizeof(struct node));
32: if (!p)
33: {
34: cout << "memory allocation error!" << endl;
35: exit(0);
36: }
37: p->data = rand()%10;
38: q->next = p;
39: q = p;
40: }
41: q->next = NULL; //尾节点切记不要出现野指针
42: return head;
43: }
44:  
45: //排序规则:第一轮把前两个节点摘出来,一个是prior,一个是p
46: //p后面的那个节点记为q,以q为首的剩余节点是待排序链表,搞
47: //一个循环,q后面那个节点记为next,q插到新链表中后,next就
48: //成了q,直到……天荒地老
49: //要点:1.头结点为空,这样前驱节点就省事很多了
50: Link sortList(Link head)
51: {
52: Link p, q, prior, next;
53: p = head->next;
54: if (p)
55: {
56: q = p->next;
57: p->next = NULL;
58: }
59: while(q)
60: {
61: prior = head;
62: p = prior->next;
63: while(p && p->data<q->data)
64: {
65: prior = p;
66: p = p->next;
67: }
68: next = q->next;
69: prior->next = q;
70: q->next = p;
71: q = next;
72: }
73: return head;
74: }
75: void printlist(Link head)
76: {
77: Link p = head->next;
78: do
79: {
80: cout << p->data << "\t";
81: p = p->next;
82: } while (p->next!=NULL);
83: cout << p->data << endl;
84: }
85: int main()
86: {
87: Link head = createlist();
88: cout << "排序前:" << endl;
89: printlist(head);
90: sortList(head);
91: cout << "排序后:" << endl;
92: printlist(head);
93:  
94: cout << system("pause");
95: return 0;
96: }
运行结果展示:
顺便提一下随机数生成:
种子: srand((unsigned)time(NULL))
随机数生成:rand();
随机数生成 0--RAND_MAX(0x7fff) 之间的数
相同种子生成相同随机数
头文件 stdlib.h       时间函数在 time.h
屡伤我心的共用体:共用体中几个变量共用一个内存区,共用体变量的地址和它各成员的地址都是同一地址
1: union
2: {
3: short k;
4: char c[4];
5: }a;
6: a.c[0] = 6;
7: a.c[1] = 2;
8: cout << a.k << endl;
输出结果是:518  (0000001000000110)
验证了变量共用地址的事实。对于上面的结果我有点绕不过来,看结果内存中的顺序是C[1]然后c[0],是按照高位在前的顺序!高字节在前!记住!
负数取余:-19%4=?不要想太多了,跟整数一样,再加上负号
1: int i=3,k;
2: k = (i--)+(i--)+(i--);
3: cout << k << endl<< i<< endl;
上面的程序输出结果为:9 0;大意失荆州啊!
int a = 1, b = 2; cout << a+++b << endl;
编译系统会自左而右将尽可能多的若干个字符组成一个运算符,于是a+++b等价于(a++)+b
逻辑运算的对象是数值型数据,当然,像布尔、字符型这种……你懂的;bool类型的数据不管是什么,输出就是0或者1
1: char str[] ={'A','B','C','\0','D','E','F','\0'},*p;
2: for (p = str; p - str < sizeof(str); p++)
3: printf("%s\n",p++);
输出结果:
上面这道题暴漏了我的很多问题,值得深思:
printf或者cout在遇到字符指针的时候会将指针作为首地址,向下输出字符,知道遇到’\0’为止
sizeof在计算字符串长度时会算上’\0’,比strlen多算一个字节