链表

题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;
}
原文地址:https://www.cnblogs.com/fuxianfeng1988/p/3298789.html