在链接列表

时间:2016-12-10 06:17:21

标签: c linked-list

我需要在C中链接列表中分隔偶数节点和奇数节点。

示例:

原始清单:3,1,8,2,5,6
改变后:8,2,6,3,1,5

当头部列表数据是奇数时,我遇到了问题,它正在切除偶数。

示例:

原始清单:3,1,8,2,5,6
改变后:3,1,5

typedef struct Node {
    int data;            // store information
    struct Node * next;  //referance to the next node
}Node;

Node * create(Node * L, int value)
{
    Node *current = L ,* new_node = (Node*)malloc(sizeof(Node)); // create and allocate a node 
    new_node->data = value;
    new_node->next = NULL;
    if (L == NULL)
    {
        L = new_node;
        current = new_node;
    }
    else
    {
        while (current->next != NULL)
            current = current->next;
        current->next = new_node;
        current = new_node;
    }
    return L;
}

Node * Change_Even_Odd(Node * L)
{
        Node *oddhead = NULL, *evenhead = NULL, *lastodd = NULL, *lasteven = NULL, *current = L;
        while (current != NULL)
        {
            // if current is even node
            if (current->data % 2 == 0)
            {
                if (evenhead == NULL)
                {
                    evenhead = current;
                    lasteven = current;
                }
                else
                {
                    lasteven->next = current;  // to connect the node to the list in the end
                    lasteven = current;  // final list
                }
            }
            else
            {
                // if current is odd node
                if (oddhead == NULL)
                {
                    oddhead = current;
                    lastodd = current;
                }
                else
                {
                    lastodd->next = current;
                    lastodd = current;
                }

            }
            current = current->next;
        }

            if (evenhead != NULL) // to put the even node in the head list
                L = evenhead;
            if (lasteven != NULL)  // link the odd nodes to the even nodes
                lasteven->next = oddhead;
            if (lastodd != NULL)  //end of list
                lastodd->next = NULL;

        return L;

}


void Print_List(Node * head)
{
    while (head != NULL)
    {
        printf("%4d", head->data);
        head = head->next;
    }
}

int main()
{
    Node * list = NULL;  //empty linked list
    srand(time(NULL));
    int i, size = rand() % 10 + 1;
    for (i = 0; i < size; i++)
        list = create(list, rand() % 10 + 1);
    printf("%d\n",size);
    Print_List(list);
    printf("\n");
    Change_Even_Odd(list);
    Print_List(list);
    printf("\n");   
}

1 个答案:

答案 0 :(得分:0)

Change_Even_Odd(list);应该为list = Change_Even_Odd(list);(我已经指出。)                     –́BLUEPIXY