删除链表中的倒数第K个结点(双(快、慢)指针)
#include <stdio.h>
typedef struct ListNode
{
int data;
struct ListNode *next;
}Node;
void CreateList(Node **head, int *arr, int n);
Node *kNode(Node *head, int k);
void printNode(Node *mmp);
int main()
{
Node *head = NULL;
int arr[6] = {45, 12, 56, 78, 68, 66};
CreateList(&head, arr, 6);
printNode(head);
Node *mmp = kNode(head, 3);
printNode(mmp);
}
void CreateList(Node **head, int *arr, int n)
{
Node *tail = NULL;
for(int i = 0; i < n; i++)
{
Node *tmp = (Node *)malloc(sizeof(Node));
tmp->next = NULL;
tmp->data = arr[i];
if(*head == NULL)
*head = tmp;
else
tail->next = tmp;
tail = tmp;
}
}
//利用快慢指针找中间结点LeetCode-876
//快指针每次走两步 慢指针每次走一步
Node *kNode(Node *head, int k)
{
if(head == NULL || k <= 0)
return NULL;
Node *slow = head;
Node *fast = head;
//一定要写为fast && fast->next 不能写为fast->next && fast
//因为fast可能指向NULL 无fast->next 写在前面会导致空指针异样
while(k--)
{
fast = fast->next;
}
if(fast == NULL)
return head->next;
while(fast->next)
{
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return head;
}
//打印链表
void printNode(Node *mmp)
{
while(mmp)
{
printf("%d ", mmp->data);
mmp = mmp->next;
}
printf("\n");
}