数据结构之单链表

来源:互联网 发布:mac jenkins 配置 编辑:程序博客网 时间:2024/05/18 01:22

之前一直不理解链表,就把它想的很具体,好像真的是个链子呢。

其实就是数据的一种组织形式吧。今天把链表的建立,求长度,删除,添加,排序,自己上机实现了下。当然也是看着别人编的写的。

// creat.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"using namespace std;typedef struct student{int data;struct student *next;}node;node* creat(){node *head,*p,*s;int x,cycle=1;head =(node*)malloc(sizeof(node));p=head;while(cycle){printf("\nPlease input the data:");scanf("%d",&x);if (x!=0){s=(node*)malloc(sizeof(node));s->data=x;printf("\n%d",s->data);p->next=s;p=s;}elsecycle = 0;}head = head->next;p->next = NULL;printf("\n 链表最后一个数据为: %d",p->data);return head;}int length(node *head){  int n=0;  node *p;  p=head;  while(p!=NULL)  {    p=p->next;n++;  }  return n;}void print(node *head){node *p;int n;n=length(head);printf("\nnow,these %d records are: \n",n);p=head;for(int i =1;i<=n;i++){if (head!=NULL&& i<n){if(p!=NULL)printf("%d->",p->data);p=p->next;}elseprintf("%d",p->data);}}node* del(node* head, int num){  node *p1,*p2;  p1=head;  while(num!=p1->data&& p1->next!=NULL)  {    p2=p1;p1=p1->next;  }  if(num==p1->data)  {  if(p1==head)  {  head=p1->next;  free(p1);  }   else  {  p2->next=p1->next;      free(p1);  }   }  else  printf("\n%d cound not been found",num);  return head;  }node* insert(node* head, int num)  //有序插入{node* p0,*p1,*p2;p1=head;p0=(node*) malloc(sizeof(node));p0->data=num;/*  在有序表中添加,考虑是表头,表中还是表尾*/while(p0->data>p1->data && p1->next!=NULL){p2 = p1;p1 = p1->next;}if(p0->data<=p1->data){if (head ==p1){p0->next = p1;head =p0;}else{p2->next=p0;p0->next=p1;}}else{p1->next = p0;p0->next = NULL;}/*在表尾部加while(p1->next!=NULL)  p1 = p1->next;p1->next = p0;p0->next = NULL;*//*在表头加p0->next = p1;head =p0;    *///在表中间加return head;}node* sort(node* head){node* p,*p2, *p3;int n,temp;n=length(head);if (head==NULL|| head->next ==NULL)return head;p=head;for (int j=1;j<n;j++){p=head;for (int i=0; i<n-j;i++){if(p->data>p->next->data){temp = p->data;p->data = p->next->data;p->next->data=temp;}p=p->next;}}return head;}void main(){node* head = NULL;int num ;head = creat();print(head);printf("\n请输入你想删除的数据:");scanf("%d",&num);head = del(head,num);print(head);  printf("\n请输入你想添加的数据:");scanf("%d",&num);head = insert(head,num);print(head);    head =sort(head);    printf("\n排序后的数据为:");print(head);}


对于链表的倒置,

还有一些排序算法总结一下,查找算法

还有双链表,循环链表的操作。

其他数据结构队列,栈,堆,树,图,哈希表等要一一学习。

都怪买的书到的晚,自己到现在才看,后天就考试了。╮(╯▽╰)╭,希望自己好运,当然自己也会继续学下去的。

 

原创粉丝点击