假设你有一个链表, 输出两两翻转后的链表

// 假设你有一个链表, 输出两两翻转后的链表  // 1->2->3->4->5->6->7  // 2->1->4->3->6->5->7// 你必须定义一个 `main()` 函数入口。

#include <iostream>

using namespace std;

struct node {

  int val;

  node* next;

};

// 这是我的答案, 经过验证已经正确, 但是有一点内存泄漏.

node* reverse(node* root) {

  // 1. add a super input

  node* super_input = new node;

  super_input->val = -1;

  super_input->next = root;

  // 2. init  ptrs

  node* cur = super_input;

  while(cur->next && cur->next->next) {

    node* tail = cur->next->next->next;

    node* first =cur->next;

    cur->next = cur->next->next;

    cur->next->next = first;

    first->next = tail;

    cur = first;

  }

  return super_input->next;

}

//thanks

node* reverse_2(node* root) {

  node* a = root;

  node* b = root->next;

  node* temp;

  node* p = NULL;

  node* n=b==NULL?a:b;

  while(b!=NULL){

    temp=b->next;

    b->next=a;

    a->next=temp;

    if(p!=NULL){

      p->next=b;

    }

    if(temp==NULL)

    {

      break;

    }

    p=a;

    a=temp;

    b=temp->next;

 }

  return n;

}

void print(node* root) {

  while(root) {

    cout << root->val << " ";

    root = root->next;

  }

  cout << endl;

}

int main() {

  node* root = new node;

  root->val = 1;

  root->next = new node;

  root->next->val = 2;

  root->next->next = new node;

  root->next->next->val = 3;

  root->next->next->next = new node;

  root->next->next->next->val = 4;

  root->next->next->next->next = new node;

  root->next->next->next->next->val = 5;

  root->next->next->next->next->next = NULL;

  //node* ret = reverse(root);

  node* ret = reverse_2(root);

  print(ret);

  return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值