这里算法的思路很简单,就是利用双指针进行定位,笔记主要记录的是C++的一些基础知识,也就是关于指针传递的一些知识。
bool DeleteListNode(int k, list& List)传入的是链表指针的引用,也就是直接操作实参链表,好处是当需要删除首指针时,可以将链表的head向next赋值即可,如果用bool DeleteListNode1(int k, node* List),在delete List之后,实参指针将指向的是一个被删除的指针,尽管在调用的函数中也进行的next赋值,但是要知道的是指针传参也是一种传值操作,也就是在函数中声明了一个变量他的地址也形参的地址不一样,只是保存的值(指针(也就是一个地址))一样,当删除该指针之后,实参中的指针也被删除了,我们next赋值操作的是在栈中,当结束之后,实参并没有进行next赋值操作,也就不能达到效果,所以解决方法就是传入引用。
// ListNode.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
//删除链表倒数第K个节点
typedef struct node {
int val;
node* next;
node(int val_) :val(val_), next(NULL) {}
}node,*list;
bool DeleteListNode(int k, list& List)
{
list slow = List;
list fast = List;
while (k > 0)
{
if (fast == NULL)
return false;
fast = fast->next;
k--;
}
if (fast == NULL)
{
list temp = List;
List = temp->next;
delete temp;
return true;
}
while (fast->next != NULL)
{
fast = fast->next;
slow = slow->next;
}
list temp = slow->next;
slow->next = temp->next;
delete temp;
return true;
}
bool DeleteListNode1(int k, node* List)
{
list slow = List;
list fast = List;
while (k > 0)
{
if (fast == NULL)
return false;
fast = fast->next;
k--;
}
if (fast == NULL)
{
list temp = List;
List = temp->next;
delete temp;
return true;
}
while (fast->next != NULL)
{
fast = fast->next;
slow = slow->next;
}
list temp = slow->next;
slow->next = temp->next;
delete temp;
return true;
}
void printList(list List)
{
while (List != NULL)
{
cout << List->val << " ";
List = List->next;
}
cout << endl;
}
int main()
{
list n1 = new node(0); list n2 = new node(1);
list n3 = new node(2); list n4 = new node(3);
n1->next = n2; n2->next = n3; n3->next = n4;
printList(n1);
bool res = DeleteListNode(4, n1);
printList(n1);
return 0;
}