看代码:#include <stdio.h>#include <stdlib.h>#include <malloc.h>typedef struct node { int data; struct node* next;} node, *list;// 判断链表是否为升序,是的话返回 1,不是返回 0int is_asc(list head){ list p = head; while (p->next != NULL) { if (p->data > p->next->data) // 如果前一个比后一个大,说明不满足升序 { return 0; } p = p->next; } return 1;}// 根据数组构建链表list build_list(int* arr, int n){ list head = (list) malloc (sizeof(node)); head->data = arr[0]; list p = head; int i; for (i = 1; i < n; i++) { p->next = (list) malloc (sizeof(node)); p->next->data = arr[i]; p = p->next; } p->next = NULL; return head;}// 输出链表void print_list (list head){ list p = head; printf ("%d", p->data); p = p->next; while (p != NULL) { printf (" -> %d", p->data); p = p->next; } printf ("\n");}int main(){ int arr[] = {0, 1, 2, 3, 4, 5, 6}; list head = build_list(arr, 7); printf ("链表为:"); print_list(head); printf ("是否是升序:%d\n", is_asc(head)); int arr2[] = {0, 1, 2, 4, 3, 5, 6}; list head2 = build_list(arr2, 7); printf ("链表为:"); print_list(head2); printf ("是否是升序:%d\n", is_asc(head2));return 0;}运行:
阅读全文 >