【数据结构】-线性表-链表 熟练度max=4(split)

设计一个算法,将一个有头结点A的单链表分解成两个链表A,B,使A中只有奇数,B中只有偶数,并且保持原来的相对顺序

输入 10 9 8 7 6 5 4 3 2 1

输出

A:9 7 5 3 1
B:10 8 6 4 2

#include<stdio.h>
#include<stdlib.h>
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode ;
void saveListhead(LNode *&L,int x[])//头插法
{
    L=(LNode *)malloc (sizeof(LNode));
    L->next=NULL;

    LNode *q,*s;
    q=L;
    for(int i=0;i<10;i++)
    {
        s=(LNode *)malloc(sizeof(LNode));
        s->data = x[i];

        s->next = q->next;
        q->next = s;
    }
}
void split(LNode *&A,LNode *&B)
{
    B=(LNode *)malloc(sizeof(LNode));
    B->next=NULL;

    LNode *a,*b,*c;
    a=A;
    b=B;
    while(a->next!=NULL)//要进行删除操作,必须指向要删除的前一个
    {
        if(a->next->data%2==0)//偶数,只能尾插,头插就reverse了
        {
            c=a->next;
            a->next=c->next;
            c->next=NULL;
            b->next=c;
            b=c;
        }
        else
        {
            a=a->next;
        }
    }
}
void printList(LNode *L)
{
    LNode *q;
    q=L->next;
    int i=0;
    while(q!=NULL)
    {
        if(i++)
            putchar(' ');
        printf("%d",q->data);
        q=q->next;///忘记写了 ------------------陷入无限循环
    }
    printf("\n");
}
int main (void)
{
    LNode *L,*B;
    int x[10]={1,2,3,4,5,6,7,8,9,10};
    saveListhead(L,x);
    printList(L);
    split(L,B);
    printList(L);
    printList(B);
    return 0;
}

关键部分

void split(LNode *&A,只能尾插,头插就reverse了
        {
            //关键部分开始
            c=a->next;
            a->next=c->next;
            c->next=NULL;
            b->next=c;
            b=c;
            //关键部分结束
        }
        else
        {
            a=a->next;
        }
    }
}

相关文章

【啊哈!算法】算法3:最常用的排序——快速排序       ...
匿名组 这里可能用到几个不同的分组构造。通过括号内围绕的正...
选择排序:从数组的起始位置处开始,把第一个元素与数组中其...
public struct Pqitem { public int priority; ...
在编写正则表达式的时候,经常会向要向正则表达式添加数量型...
来自:http://blog.csdn.net/morewindows/article/details/6...