zoukankan      html  css  js  c++  java
  • 在单链表中删除倒数第K个节点(C++实现)

    代码:

    #include <iostream>
    class Node{
    public:
      int value;
      Node* next;
      Node(int data){
        this->value = data;
      }
    } *node;

    Node* removeLastKthNode(Node* head,int lastKth){
    if(head==nullptr || lastKth < 1){
      return head;
    }
    Node* cur = head;
    while(cur != nullptr){
      lastKth--;
      cur = cur->next;
    }
    if(lastKth == 0){
      head = head->next;
    }
    if(lastKth<0){
      cur = head;
      while(++lastKth != 0){
        cur = cur->next;
      }
      cur->next = cur->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;
    }
    removeLastKthNode( head,2);
    std::cout  << ' ';
    Node* tem = head;
    while(tem!=nullptr)
    {
      std::cout << tem->value << ' ';
      tem = tem->next;
    }
    }
     
    测试结果:
     
     
  • 相关阅读:
    Java8 Period.between方法坑及注意事项
    mybatis入门-第一个程序
    mybatis入门-框架原理
    初识servlet--未完成
    初识servlet
    session是什么
    session工作原理简介
    笔记本维修介绍
    j2se 总结
    maven
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13473240.html
Copyright © 2011-2022 走看看