在双向链表中删除倒数第K个链表节点(C++实现)

代码:

#include <iostream>
class DoubleNode{
public:
  int value;
  DoubleNode* last;
  DoubleNode* next;
  DoubleNode(int data){
    this->value = data;
  }
};
DoubleNode* removeLastKthNode(DoubleNode*head,int lastKth){
  if(head == nullptr || lastKth < 1){
    return head;
  }
  DoubleNode* cur = head;
  while(cur!=nullptr)
  {
    lastKth--;
    cur = cur->next;
  }
  if(lastKth==0){
    head = head->next;
    head->last = nullptr;
  }
  if(lastKth < 0)
  {
    cur = head;
    while(++lastKth != 0){
      cur = cur->next;
    }
    cur->next = cur->next->next;
    if(cur->next->next!=nullptr){
      cur->next->next->last = cur;
    }
  }
  return head;
}
int main()
{
DoubleNode* node1 = new DoubleNode(1);
DoubleNode* node2 = new DoubleNode(2);
DoubleNode* node3 = new DoubleNode(3);
DoubleNode* head = node1;
node1->last = head;
node1->next = node2;
node2->last = node1;
node2->next = node3;
node3->last = node2;
node3->next = NULL;
DoubleNode* cur = head;
while(cur!=nullptr){
  std::cout << cur->value << ' ';
  cur = cur->next;
}
removeLastKthNode( head,2);
std::cout  << '\n';
DoubleNode* tem = head;
while(tem!=nullptr)
{
  std::cout << tem->value << ' ';
  tem = tem->next;
}
}
 
测试结果:
 

 

 

posted @ 2020-08-11 13:52  诗和远方*  阅读(211)  评论(0)    收藏  举报