单链表的创建/打印/求长/两两反转/排序

#include <string>
#include <iostream>
using namespace std;
struct Node{
    int val;
    Node *next;
};
Node *creat(){
    int x =0 ;
    Node *head,*p;
    head = new Node; //关键 给head分配空间
    p=head;
    while(cin>>x){
        Node *s = new Node;
        s->val = x;
        p->next = s;
        p=s;
        if (getchar() == '\n')  break;  //关键 不然while(cin>>n)需要ctrl+z才能结束
    }
    head = head->next;
    p->next = NULL;
    return head;
}
int length(Node *head){
    if(head==NULL)  return 0;
    int count=0;
    Node *p;
    p=head;
    while(p!=NULL){
        p=p->next;
        count++;
    }
//    while(head!=NULL){
//        head=head->next;
//        count++;
//    }
//    cout<<count<<endl;
    return count;
}
void print(Node * head){
    Node *p ;
    p=head;
    while(p!=NULL){
        cout<<p->val<<" ";
        p = p->next;
    }
    cout<<endl;
}
Node *reverse(Node *head){
    Node *ans = new Node;
    ans->next = head;
    Node *cur = ans;
    while(cur->next!=NULL && cur->next->next!=NULL){
        Node* node1 = cur->next;
        Node* node2 = node1->next;
        Node* rear = node2->next;
        cur->next = node2;
        node2->next = node1;
        node1->next = rear; //这一步改变了head->next,跳过了第二个
        cur = node1;

    }
    return ans->next;
}

Node *sort(Node *head){
    Node *p = head;
    int nums = length(head);
    int tmp;
    for(int i=0;i<nums-1;i++){
        p = head;
        for(int j=0;j<nums-i-1;j++){
            if(p->val > p->next ->val){
                tmp = p->val;
                p->val = p->next ->val;
                p->next ->val = tmp;
            }
            p = p->next;
        }
    }
    return head;
}

int main() {
    Node * head;
    head = creat();
    Node *s = sort(head);
    print(s);
    Node * rev = reverse(head);
    print(rev);

}

猜你喜欢

转载自www.cnblogs.com/whalelife/p/10502382.html