- #include<iostream>
- #include<stdio.h>
- #include<string.h>
- #include<stdlib.h>
- //#include<conio.h>
- using namespace std;
- class Node
- {
- public:
- int data;
- Node* next;
- };
- Node* create()
- {
- Node* head,*p,*s;
- int x,cycle=1;
- head=(Node*)new Node;
- p=head;
- while(cycle)
- {
- printf("\\nplease input the data:");
- scanf("%d",&x);
- if(x!=0){
- s=(Node*)new Node;
- s->data=x;
- // printf("\\n%d",s->data);
- p->next=s;
- p=s;
- }
- else cycle=0;
- }
- head=head->next;
- p->next=NULL;
- printf("\\nhead data is: %d\\n",head->data);
- return (head);
- }
- Node* Delete(Node* head,int num)
- {
- Node* p1,*p2;
- p1=head;
- while(num!=p1->data&&p1->next!=NULL)
- {
- p2=p1;//前一个node
- p1=p1->next;
- }
- if(num==p1->data)
- {
- if(p1==head)
- {
- head=p1->next;
- delete p1;
- }
- else{
- p2->next=p1->next;
- delete p1;
- }
- }
- else
- printf("\\n%d could not been found ",num);
- 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;
- p=head;
- while(p!=NULL){
- printf("%d->",p->data);
- p=p->next;
- }
- printf("\\n");
- }
- Node* insert(Node* head,int num)
- {
- Node* p0,*p1,*p2;
- p1=head;
- p0=(Node*) new 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;
- }
- return (head);
- }
- Node* sort(Node* head)
- {
- Node*p,*p2,*p3;
- int n;
- int 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;
- }
- 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=create();
- printf("\\nlist length is:%d\\n",length(head));
- printf("********list data is*************\\n");
- print(head);
- head=Delete(head,4);
- printf("\\nafter delete list length is %d\\n",length(head));
- printf("********list data is************\\n");
- print(head);
- cout<<"************INSERT*****************"<<endl;
- head=insert(head,888);
- cout<<"after insert list length is "<<length(head)<<endl;
- cout<<"**********list data is***********"<<endl;
- print(head);
- cout<<"**********SORT****************"<<endl;
- head=sort(head);
- print(head);
- cout<<"**********REVERSE*******************"<<endl;
- head=reverse(head);
- print(head);
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/0412201411177.html
来源: http://www.codesnippet.cn/detail/0412201411177.html