在数据结构中,链表无疑是最基本的,也是在大多数IT公司面试笔试中考察最多的;有了扎实的处理链表的基础,对以后学习更复杂的数据结构类型是很有帮助也是很有必要的;因此在闲暇时间中,又再一次重写了对于链表的一些基本操作,也参考了一些资料,在此将代码分享一下,希望对初学者有所帮助。
一开始的时候,对于链表的建立,都会这样来写,基本上都会用到两次malloc函数的调用。代码大致上如下所示。
//创建长度为n的单链表 node *create(int n) { node *head,*precious,*current; int cnt; int label = 1; for(cnt = 0;cnt < n;cnt++) { if(label == 1) { precious = (node *)malloc(sizeof(node)); printf("Input the information just like:name ID gender age \n"); scanf("%s%s%s%d",precious->name,precious->ID,precious->s,&precious->age); precious->link = NULL; head = precious; label = 0; } else { current = (node*)malloc(sizeof(node)); printf("Input the information just like:name ID gender age \n"); scanf("%s%s%s%d",current->name,current->ID,current->s,¤t->age); // current->link = NULL; precious->link = current; precious = current; } } precious->link = NULL; return head; }
//建立链表 node *CreatLink(int n) { node *head,*p,*q; for(int i=1; i<n+1; i++) { p = (node*)malloc(sizeof(node)); printf("input a number:"); scanf("%d",&p->data); if(i == 1) head = p; else q->next = p; q = p; p->next = NULL; } return head; }
下面的代码参考了一些资料(如程序员面试宝典、谭浩强的书)
插入结点
node *Insert(node *head,int num) { node *p,*q,*s; s = (node*)malloc(sizeof(node)); printf("input a number:"); scanf("%d",&s->data); p = head; //先寻找到相应位置再处理,假设数据已按升序排列 while(p->data < s->data && p->next != NULL) { q = p; p = p->next; } if(p == head) {head = s; p = s->next;} else if(p->next == NULL) { p->next = s; s->next = NULL; } else { q->next = s; s->next = p; } return head; }
node *Delete(node *head,int num) { node *p,*q; p = head; //先查找再删除 while(p->data != num && 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("%d could not been found",num); return head; }
以下是一个用冒泡法写的一个链表排序
node *Sort(node* head,int length) { node *p; for(int i = 1; i < length ; i++) { p = head; for(int j = 0; j < length - i ; j++) { if(p->data > p->next->data) { int tmp = p->data; p->data = p->next->data; p->next->data = tmp; } p = p->next; } } return head; }