标签:
// 定义链表的数据结构 typedef struct _LINK_NODE{ int data; struct _LINK_NODE * next; }LINK_NODE; //创建一个单向链表 LINK_NODE * create(){ int inputFlag = 1,value; LINK_NODE *head,*p,*s; head = (LINK_NODE *)malloc(sizeof(LINK_NODE)); p = head; while (inputFlag) { printf("请输入阿拉伯数字,0结束输入:\n"); scanf("%d",&value); if (value != 0) { s = (LINK_NODE *)malloc(sizeof(LINK_NODE)); s->data = value; p->next = s; p = s; }else{ inputFlag = 0; } } p->next = NULL; head = head->next; return head; } //得到链表的长度 int length(LINK_NODE * head){ int length = 0; LINK_NODE *p = head; while (p != NULL) { p = p->next; length++; } return length; } //打印单链表 void print(LINK_NODE * head){ LINK_NODE *p = head; while (p) { printf("%d ",p->data); p = p->next; } } //删除指定的数据 LINK_NODE * delete(LINK_NODE * head,int num){ LINK_NODE *p,*q; p = head; while (num != p->data && p->next != NULL) { q = p; p = p->next; } if (num == p->data) { if (p == head) { head = p->next; free(p); }else{ q->next = p->next; free(p); } }else{ printf("没找到"); } return head; } //进行排序 选择排序 LINK_NODE * sort(LINK_NODE * head){ LINK_NODE *p; if (head == NULL && head->next == NULL) { return head; } int len = length(head); for (int i = 0; i < len - 1; i++) { p = head; for (int j = i + 1; j < len; j++) { if (p->data > p->next->data) { int temp = p->data; p->data = p->next->data; p->next->data = temp; } p = p->next; } } return head; } //链表倒序 LINK_NODE * reverse(LINK_NODE * head){ if (head == NULL && head->next == NULL) { return head; } int len = length(head); int a[len]; int i = 0; LINK_NODE *p = head; while (p != NULL) { a[i++] = p->data; p = p->next; } LINK_NODE * newHead,*link,*s; newHead = (LINK_NODE *)malloc(sizeof(LINK_NODE)); link = newHead; for (int k = len - 1; k >= 0;k--) { s = (LINK_NODE *)malloc(sizeof(LINK_NODE)); s->data = a[k]; link->next = s; link = s; } newHead = newHead->next; link->next = NULL; return newHead; } // int main(int argc, const char * argv[]){ LINK_NODE * head = create(); printf("%d\n",length(head)); print(head); printf("\n"); print(sort(head)); printf("\n"); print(reverse(head)); //print(delete(head, 5)); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/qq1791422018/article/details/47357781