输入无序的元素,分别建立两个有3个元素结点的有序单链表(无头结点)(显示排序后的链表),交换两个单链表的第一个结点(注意不能采取直接赋值的方式,要进行结点的移动),最后显示链表中元素

输入无序的元素,分别建立两个有3个元素结点的有序单链表(无头结点)(显示排序后的链表),交换两个单链表的第一个结点(注意不能采取直接赋值的方式,要进行结点的移动),最后显示链表中元素

创建链表的时候就按值的顺序插入合适的位置,用临时指针记录某一个头结点,交换链表头

输入6个元素,前3个放在链表1中,后3个放在链表2中,插入链表是按照升序插入。然后交换两个头结点。

运行结果如下:

img

代码:

#include <stdio.h>
#include <stdlib.h>
struct StNode 
{
    int data;
    struct StNode* next;
};

int main()
{
    struct StNode* head1=0,*head2=0;
    struct StNode* p1,*p2,*t;
    int i,n;
    
    printf("请输入6个整数:");
    //前3个插入链表1
    for(i=0;i<3;i++)
    {
        t = (struct StNode*)malloc(sizeof(struct StNode));
        scanf("%d",&t->data);
        t->next = NULL;
        if(head1 == 0)
        {
            head1 = t;
            p1 = t;
        }else
        {
            p1 = head1;
            if(head1->data > t->data)
            {
                t->next = head1;
                head1 = t;
            }else
            {
                while(p1->next && p1->next->data < t->data)
                    p1 = p1->next;
                if(p1->next)
                    t->next = p1->next;
                p1->next = t;
            }
            
        }
    }
    
    
    //后3个插入链表2
    for(i=0;i<3;i++)
    {
        t = (struct StNode*)malloc(sizeof(struct StNode));
        scanf("%d",&t->data);
        t->next = NULL;
        if(head2 == 0)
        {
            head2 = t;
            p2 = t;
        }else
        {
            p2 = head2;
            if(head2->data > t->data)
            {

                t->next = head2;
                head2 = t;

            }else
            {
                while(p2->next && p2->next->data < t->data)
                    p2 = p2->next;
                if(p2->next)
                    t->next = p2->next;
                p2->next = t;
            }

        }
    }

    //交换链表头
    t = head2->next; //
    head2->next = head1->next;
    head1->next = t;

    //打印链表
    t=head1;
    printf("链表1:");
    while(t)
    {
        printf("%d ",t->data);
        t = t->next;
    }

    printf("\n链表2:");
    t = head2;
    while(t)
    {
        printf("%d ",t->data);
        t = t->next;
    }

    //释放空间
    while(head1)
    {
        t = head1->next;
        free(head1);
        head1 = t;
    }
    while(head2)
    {
        t = head2->next;
        free(head2);
        head2 = t;
    }
    head1 = 0;
    head2 = 0;
    return 0;
}