//编程实现一个单链表的建立/长度/打印 #include<iostream> #include<cstring> #include<cstdio> #include<conio.h> #include<stdlib.h> using namespace std; typedef struct student { int data; struct student *next; }node; node *creat()//单链表的建立 { node *head,*p,*s; int x,cycle=1; head=new node; p=head; while(cycle) { printf("input the data "); scanf("%d",&x); if(x!=0) { s=new node; s->data=x; p->next=s; p=s; } else cycle=0; } head=head->next; p->next=NULL; return head; } node *del(node *head,int num)//实现单链表删除节点。 { node *p,*q; p=head; while(p->next!=NULL) { if(p->data==num) { if(p==head) { head=p->next; free(p); return head; } else { //printf("p=%d,q=%d ",p->data,q->data); q->next=p->next; } } q=p; p=p->next; } return head; } node *insert(node *head,int num) { node *p0,*p1,*p2; p1=head; p0=new node; p0->data=num; while(p0->data>p1->data&&p1->next!=NULL) { p2=p1;p1=p1->next; } // printf("p0=%d,p1=%d,p2=%d ",p0->data,p1->data,p2->data); 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; } return (head); } void print(node *head)//单链表打印 { node *p=head; p=head; while(p!=NULL) { printf("%d ",p->data); p=p->next; } printf(" "); } int length(node *head) { int n=0; node *p; p=head; while(p!=NULL) { p=p->next; n++; } return n; } node *sort(node *head) { node *p; int n=length(head); int i,j,temp; if(head==NULL||head->next==NULL) return head; p=head; for(i=0;i<n;i++) { p=head;//??????? for(j=i+1;j<n;j++) { if(p->data>p->next->data) { temp=p->data; p->data=p->next->data; p->next->data=temp; } p=p->next; } } return head; } node *reverse(node *head)//单链表的逆置 { node *p1,*p2,*p3; if(head==NULL||head->next==NULL) return head; p1=head; p2=p1->next; while(p2) { p3=p2->next; p2->next=p1; p1=p2; p2=p3; } head->next=NULL; head=p1; return head; } int main() { node *head; head=creat(); printf("创建链表为 "); print(head); int t1,t2; printf("请输入删除的数 "); scanf("%d",&t1); head=del(head,t1); print(head); printf("请输入插入的数 "); scanf("%d",&t2); head= insert(head,t2); print(head); printf("单链表排序从小到大 "); head=sort(head); print(head); printf("链表逆置 "); head=reverse(head); print(head); return 0; }