Demo entry 6761869

线性表的操作

   

Submitted by 杨曾严 on Oct 06, 2018 at 12:11
Language: C++. Code size: 2.2 kB.

#include <iostream>  
using namespace std;  
//节点的定义  
class Node  
{  
public:  
    Node()  
    {  
        next = NULL;  
        data = 0;  
    }  
    Node(int n)  
    {  
        next = NULL;  
        data = n;  
    }  
    int data;  
    Node *next;  
};  
//打印链表  
void show(Node *first)  
{  
    Node *p;  
    p = first->next;  
    while(p != NULL)  
    {  
        cout << p->data << " ";  
        p = p->next;  
    }  
    cout << endl;  
}  
//创建非递增有序表  
void build(Node *front,int size)  
{  
    /* 
    front指整条序列 
    p指新插入的节点 
    curr为新插入节点的下一个节点 
    pre为前一个 
    */  
    Node *curr,*pre,*p;  
    cout <<"please input the data: "<<endl;  
    for(int i = 0 ; i < size ; i++)  
    {  
        int data;  
        curr = front->next;  
        //输入要插入的数字  
        cin >> data;  
        p = new Node(data);  
        pre = front;  
        while(curr != NULL && curr->data >= data)  
        {  
            pre = curr;  
            curr = curr->next;  
        }  
        p->next = curr;  
        pre->next = p;  
    }  
    show(front);        //输出该新建链表  
}  
//合并两个链表为非递减有序链表  
void Mergelist(Node *&la, Node *&lb, Node *&lc)  
{  
    Node *pa,*pb,*pc,*q;  
    pa = la->next;  
    pb = lb->next;  
    lc = pc = la;  
    lc->next = NULL;  
    while(pa || pb)  
    {  
        if(pa)         //读取整条la  
        {  
            q = pa;  
            pa = pa->next;  
        }  
        else if(pb)        //读取整条lb  
        {  
            q = pb;  
            pb = pb->next;  
        }  
        Node *curr,*pre;  
        curr = lc->next;  
        pre = lc;  
        while(curr != NULL && curr->data <= q->data)        //在新接入节点的时候进行排序  
        {  
            pre = curr;  
            curr = curr->next;  
        }  
        q->next = curr;  
        pre->next = q;  
    }  
    delete lb;  //释放头结点  
}  
int main()  
{  
    Node *str1,*str2,*str3;  
    str1 = new Node();  
    str2 = new Node();  
    build(str1,6);  
    build(str2,5);  
    Mergelist(str1,str2,str3);  
    show(str3);  
    return 0;  
}  

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).