合并链表

#include <iostream>
#include<stack>
using namespace std;
struct ListNode {
  int val;
  ListNode* next;
  ListNode(int i):val(i),next(NULL){} //c++中可以给结构体中加函数,这里用来赋值
};
class List{  //链表类:头尾指针,构造析构,插入数值,打印,返回第一个数,删除,清空
public:
  ListNode * head;
  ListNode * tail;
  List();
  ~List();
  void insert(int temp);
  void print();
  int top();
  int pop();
  bool empty();
  void merge(List&l1,List&l2);
};

List::List():head(NULL),tail(NULL){
  
}

List::~List(){
  ListNode* temp; //用来移动
  temp = head;
  while(temp!=NULL){
    temp=temp->next;
    delete head;
    head = temp;
  }
}

void List::insert(int elem){
  if(tail==NULL){
    head = tail = new ListNode(elem);
  }
  else{
    tail->next = new ListNode(elem);
    tail = tail->next;
  }
}

bool List::empty(){
  if(head==NULL)
    return true;
  else
    return false;
}

int List::top(){
  return head->val;
}

int List::pop(){
  //从头部删除一个节点,那么就把那个head赋给temp,然后删掉,移动head
  if(head!=NULL){
    int it = head->val;
    ListNode* temp = head;
    delete temp;
    head = head->next;
    if(head==NULL)
      tail = NULL;
    return it;
  }
  else
    return 0;
}

void List::print(){
  //打印,如果为空,返回错误,定义一个temp,移动,temp的下一个是空的时候说明打印结束
  if(empty())
  {
   cout<<"NULL"<<endl;
    return;
  }
  else{
    ListNode* temp = head; //head里面是第一个值
    while(temp!=NULL)
    {
      cout<<temp->val<<" ";
      temp = temp->next;
      
    }
  }
  
}

void List::merge(List&l1,List&l2){
  //如果两个都不是空的,那么久比较一下哪个小,小的放第一个
  List s; //放合并后的链表
  int temp;
  while(l1.empty()==false&&l2.empty()==false){
    if(l1.top()<l2.top()){
      temp = l1.top();
      l1.pop();
      s.insert(temp);
    }else
    {
      temp = l2.top();
      l2.pop();
      s.insert(temp);
    }
  }
  while(l1.empty()==false){
    temp = l1.top();
    l1.pop();
    s.insert(temp);

  }
  while(l2.empty()==false){
    temp = l2.top();
    l2.pop();
    s.insert(temp);
    
  }
}

int main(int argc, const char * argv[]) {
  using namespace std;
  
  
  int q1,q2;
  cin>>q1; //两个链表长度
  //while (!cin.eof()) {//到文件末尾,eof=1
    
    List l1,l2,s;    //两个输入链表,一个合并后的s
    int temp;
    for (int i=0; i<q1; i++) {  //l1初始化
      cin>>temp;
      l1.insert(temp);
   }
    //for (int i=0; i<q2; i++) { //l2初始化
     // cin>>temp;
     // l2.insert(temp);
   // }
   // l1.print();
    
    stack<int> s1;
    for(int i=0;i<q1;i++)
    {
      s1.push(l1.pop());
      
    }
    for(int i=0;i<q1;i++)
    {
      l1.insert(s1.top());
      s1.pop();
      
    }
    l1.print();
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值