zoukankan      html  css  js  c++  java
  • 删除链表的中间节点(C++实现)

    代码:

    #include <iostream>
    class Node {
    public:
      int value;
      Node* next;
      Node(int data){
        this->value = data;
      }
    };
    Node* removeMidNode(Node* head){
      if(head == nullptr||head->next == nullptr){
        return head;
      }
      if(head->next->next == nullptr){
        return head->next;
      }
      Node* pre = head;
      Node* cur = head->next->next;
      while(cur->next != nullptr&&cur->next->next != nullptr){
        pre = pre->next;
        cur = cur->next->next;
      }
      while(cur->next!=nullptr&&cur->next->next!=nullptr){
        pre = pre->next;
        cur = cur->next->next;
      }
      pre->next = pre->next->next;
      return head;
    }
    int main()
    {
      Node* node1 = new Node(1);
      Node* node2 = new Node(2);
      Node* node3 = new Node(3);
      Node* node4 = new Node(4);
      Node* node5 = new Node(5);
      Node* head = node1;
      head->next = node2;
      node2->next = node3;
      node3->next = node4;
      node4->next = node5;
      node5->next = NULL;
      Node* cur = head;
      while(cur!=nullptr){
        std::cout << cur->value << ' ';
        cur = cur->next;
      }
     removeMidNode(head);
      std::cout  << ' ';
      Node* tem = head;
      while(tem!=nullptr)
      {
        std::cout << tem->value << ' ';
        tem = tem->next;
      }
    }
     
    测试结果:
     
     
  • 相关阅读:
    第五次作业
    第四次作业
    Java实验二
    java第一次作业
    第十一次作业
    第十次作业
    第九次作业
    第八次作业
    第七次作业
    第六次作业
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13494094.html
Copyright © 2011-2022 走看看