关于链表的学习,有指针等,实现了些小功能,学习用:
实现了链表的插入,删除,排序等功能;
贴出代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
#include <stdio.h> #include <stdlib.h> /*声明一个结构体,包含以下几个内容,只是用到了num、next两个参数,待扩展*/ typedef struct node { int num; char name[10]; struct node* next; struct node* previous; }lnode,*linklist; /*新建一个节点*/ void insertnode(linklist head) { linklist temp = head; linklist lnew = (linklist)malloc(sizeof(lnode)); lnew->next = NULL; while(temp->next != NULL) { temp = temp->next; } printf("insert a num:"); scanf("%d",&lnew->num); temp->next = lnew; } /*遍历链表,显示所有节点*/ void display(linklist &head) { linklist temp = head->next; while(1) { printf("%d ",temp->num); temp = temp->next; if(temp==NULL)break; } } /*对节点进行排序,升序*/ void lpsort(linklist head,int sum) { linklist temp1; linklist temp2 = (linklist)malloc(sizeof(lnode)); int i=0,j=0; /*冒泡排序*/ for(i=0;i<sum-1;i++) { temp1 = head->next; while(temp1->next != NULL) { if(temp1->num > temp1->next->num) { temp2->num = temp1->num; temp1->num = temp1->next->num; temp1->next->num = temp2->num; } temp1 = temp1->next; } } free(temp2); } int main() { int sum = 0; //声明链表头结点 linklist head = (linklist)malloc(sizeof(lnode)); head->next = NULL; char ac; printf("continue(y?n)"); while(scanf("%c",&ac)&&ac=='y') { insertnode(head); getchar(); printf("continue(y?n)"); sum++; } printf("all:%d\n",sum); display(head); printf("\nafter sort\n"); lpsort(head,sum); display(head); free(head);// 释放内存 system("PAUSE"); return 0; } |
发表评论