#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node* next; }Node; /*输出:头结点的指针*/ Node *Create() { Node *head; Node *p; Node *s; int x; int cycle = 1; // printf("sizeof(Node) = %d ", sizeof(Node)); head = (Node *)malloc(sizeof(Node)); p = head; while(cycle) { scanf("%d", &x); if (0 != x) //输入数据是0作为结束标志 { s = (Node *)malloc(sizeof(Node)); s->data = x; p->next = s; p = s; } else { cycle = 0; } } //head = head->next; //面试宝典返回的是第一个结点的指针,觉得不合理 s->next = NULL; return head; } /*测表长*/ int SqListLength(Node *sql) { int length = 0; Node *tem = sql->next; while(tem != NULL) { ++length; tem = tem->next; } return length; } /*打印线性表*/ void PrintSqList(Node *sq) { Node *tem = sq->next; while(tem != NULL) { printf("sq->data = %d ", tem->data); tem = tem->next; } } /*删除结点*/ Node *DeleteNode(Node *sq, int num) { Node *tem = sq->next; Node *fore = sq; while (tem != NULL && tem->data != num) //查找值为num的结点 { fore = tem; tem = tem->next; //printf("find it "); } if (tem->data == num) { fore->next = tem->next; //此句话是关键!!!! free(tem); printf("delete it "); } else { printf("Can't find that node! "); } return sq; } Node *InsertNode(Node *sq, int num) { Node *tem = sq->next; Node *fore = sq; Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = num; while (tem != NULL && tem->data < num) //顺序插入,找到合适的位置。 { fore = tem; tem = tem->next; printf("find it "); } fore->next = newNode; newNode->next = tem; /* if (tem != NULL) { fore->next = newNode; newNode->next = tem; } else { printf("insert failure "); }*/ return sq; } /* void BubbleSort(int arr[],int len) { int i; int j; for (i = 1; i < len; i++) { for (j = 0; j < len - i; j++) //排好顺序的元素在数组的后面 { if (arr[j] > arr[j + 1]) { int tem = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tem; } } } } void PrintArr(int arr[], int len) { printf("After sorting: "); for (int index = 0; index < len; index++) { printf("%d ",arr[index]); } }*/ /*线性表排序*/ Node *SortSq(Node *sq) { Node *p; int length = SqListLength(sq); if (length == 0 || length == 1) { return sq; } else { for (int i = 1; i < length; i++) { p = sq->next; for (int j = 0; j < length - i; j++) { if (p->data > p->next->data) //不交换结点,只交换结点中的数据 { int tem = p->data; p->data = p->next->data; p->next->data = tem; } p = p->next; } } return sq; } } int main() { /* int arr[] = {1, 3, 2, 4}; BubbleSort(arr, 4); PrintArr(arr,4);*/ Node *sq = Create(); printf("len = %d ", SqListLength(sq)); PrintSqList(sq); printf(" "); sq = SortSq(sq); PrintSqList(sq); /* sq = DeleteNode(sq, 2); PrintSqList(sq); printf(" "); sq = InsertNode(sq, 8); PrintSqList(sq); printf(" ");*/ return 0; }