• 链表


    题1:已知链表的头节点head,写一个函数把这个链表逆序

    #include<iostream>
    
    using namespace std;
    
    typedef struct Node
    {
        int data;
        struct Node *next;
    }Node;
    
    Node* CreatList(int n)
    {
        //创建链表
        Node* L= new (Node);    //(Node*)malloc(sizeof(Node))
        cout<<"please input data:";
        cin>>L->data;
        L->next=NULL;
        Node* p;
        for(int i=n-1;i>0;i--)
        {
            p= new (Node);
            cout<<"please input data:";
            cin>>p->data;
            p->next=L;
            L=p;
        }
        return L;
    }
    
    Node* ReverseList(Node *head)
    {
        Node* p1=head;
        Node* p2=p1->next;
        Node* p3=p2->next;
        p1->next=NULL;
        while(p3)
        {
            p2->next=p1;
            p1=p2;
            p2=p3;
            p3=p3->next;
        }
        p2->next=p1;
        head=p2;
        return head;
    }
    
    int main()
    {
        Node* head=CreatList(10);
        head=ReverseList(head);
        return 0;
    }

    题2:已知两个链:List1 和List2 各自有序,请把它们合并成一个链表依然有序。(保留所有结点,即便大小相同)

    #include<iostream>
    
    using namespace std;
    
    typedef struct Node
    {
        int data;
        struct Node *next;
    }Node;
    
    Node* CreatList(int n)
    {
        //创建一个带头节点的链表
        Node* L= new (Node);    //(Node*)malloc(sizeof(Node))
        L->next=NULL;
        Node* p;
        for(int i=n;i>0;i--)
        {
            p= new (Node);
            cout<<"please input data:";
            cin>>p->data;
            p->next=L->next;
            L->next=p;
        }
        return L;
    }
    
    Node* MergeList(Node* L1,Node* L2)
    {   //假设L1和L2的元素按值非递减
        Node* p1=L1->next;
        Node* p2=L2->next;
        Node* L3=L1;              //用L1的头节点作为L3的头节点
        Node* p3=L1;              //保存要插入的位置
        while(p2&&p1)
        {   
            if(p1->data>=p2->data)
            {
                p3->next=p2;
                p3=p2;
                p2=p2->next;
            }
            else
            {
                p3->next=p1;
                p3=p1;
                p1=p1->next;
            }
        }
        p3->next=p1?p1:p2;
        delete L2;
        return L3;
    }
    int main()
    {
        Node* List3;
        Node* List1=CreatList(4);
        Node* List2=CreatList(4);
        List3=MergeList(List1,List2);
        return 0;
    }
  • 相关阅读:
    引入C/C++动态库
    Linux新手常用命令
    使用Dotfunsctor
    C#上传数据到HTTP,HTTPS 代码示例
    C#多个泛型约束问题
    创建DataTable与DataGridView进行绑定
    递归迭代vector三种方法实现二路归并排序
    区间贪心算法
    递归和非递归实现二叉树的遍历
    C语言实现全排列和回溯法总结
  • 原文地址:https://www.cnblogs.com/fuxianfeng1988/p/3298789.html
Copyright © 2020-2023  润新知