#include<stdio.h> #include<assert.h> #include<stdlib.h> typedef int DataType; typedef struct SListNode { DataType data; struct SListNode* next; }SListNode; SListNode* BuyNode(DataType x) { SListNode* next = (SListNode*)malloc(sizeof(SListNode)); next->data = x; next->next = NULL; return next; } void PushBack(SListNode* & ppHead, DataType x) { if (ppHead == NULL) { ppHead = BuyNode(x); } else { SListNode* tail = ppHead; while (tail->next != NULL) { tail = tail->next; } tail->next = BuyNode(x); } } //查找单链表的倒数第k个节点,要求只能遍历一次 SListNode* FindLastKMiddle(SListNode* ppHead,DataType k) { SListNode* slow = ppHead; SListNode* fast = ppHead; while (fast !=NULL && k--) { fast = fast->next; } if (k > 0) { return NULL; } while (fast) { fast = fast->next; slow = slow->next; } return slow; } void PrintSNodeList(SListNode* ppHead) { while (ppHead) { printf("%d->", ppHead->data); ppHead = ppHead->next; } printf("\n"); } void Test3() { SListNode* List = NULL; PushBack(List, 1); PushBack(List, 2); PushBack(List, 3); PushBack(List, 4); PushBack(List, 5); PrintSNodeList(List); SListNode *ret = FindLastKMiddle(List, 4); if (ret == NULL) { printf("该值不存在!\n"); } else { printf("%d ", ret->data); } } int main() { Test3(); system("pause"); return 0; }
C语言:【单链表】查找单链表的倒数第k个节点,要求只能遍历一次
原创
©著作权归作者所有:来自51CTO博客作者韩静静的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
单链表查找倒数第k个节点
单链表查找倒数第k个节点
查找 单链表 节点 -
单链表输出倒数第k个元素
这个算法已经有不少人写过了,但是为了考研后期复习还是在此记录一
单链表 倒数第k个元素 链表 两个指针 顺序表 -
算法-查找链表中倒数第K个节点
算法-查找链表中倒数第K个节点
System i++ 算法实现 -
每日一道小算法[十三] [链表] 单链表中的倒数第k个节点
前言: 还是没坚持住每天更新一道算法题,自己不会的东西太多,每天都要看很多的东西来充实自己,所以也没有每天都刷
链表 算法 leetcode 数据结构 两个指针