分享

单链表反转与排序

 champion_xu 2012-09-07
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct mynode {
    int dat;
    struct mynode *next;
}node;

void create_node(node **list)
{
    node *p,*s,*head;
    int d;

    head = (node *)malloc(sizeof(node));
    if(head==NULL) {
        printf("Not enough memory\n");
    }

    head->next = NULL;
    p=head;

    while(1) {
        scanf("%d",&d);
        if(d==0) break;
        s = (node *)malloc(sizeof(node));
        s->dat = d;
        p->next=s;
        p=p->next;

    }
    p->next=NULL;
    head = head->next;
    *list = head;
}

int node_length(node **head)
{
    int len=0;
    node *p;
    p=*head;

    while(p!=NULL) {
        len++;
        p=p->next;
    }

    return len;
}

void node_sort(node **head)
{
    node *p;
    int i,j,len;
    int tmp;

    p = *head;
    if((p==NULL)||(p->next==NULL)) return;
    len = node_length(head);
    for(i=1;i<len;i++) {  //这是冒泡法排序
        p = *head;
        for(j=0;j<len-i;j++) {
            if(p->dat>p->next->dat) {
                tmp = p->dat;
                p->dat = p->next->dat;
                p->next->dat = tmp;
            }
            p = p->next;
        }
    }
}

void node_print(node **head)
{
    node *p;

    p = *head;
    while(p!=NULL) {
        printf("%d,",p->dat);
        p=p->next;
    }
    printf("\n");
}

void node_reverse(node **head)
{
    node *p1,*p2,*p3;
    p1=*head;
    p2=p1->next;
    while(p2) {
        p3=p2->next;
        p2->next=p1; //指向反转
        p1=p2;   //右移2个
        p2=p3;
    }
    (*head)->next=NULL;
    *head = p1;
}


int main()
{
    node *n0;
    create_node(&n0);
    node_sort(&n0);
    node_print(&n0);
    node_reverse(&n0);
    node_print(&n0);
    return 0;
}

结果:


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多