当前位置: 首页 > news >正文

链表中倒数最后k个结点【c语言】

#include <stdio.h>
#include <stdlib.h>typedef struct Node {int data;struct Node* next;
} Node, *LinkedList;// 创建一个新节点
Node* createNode(int data) {Node* newNode = (Node*)malloc(sizeof(Node));if (newNode == NULL) {printf("Error! Unable to create a new node.\n");exit(0);}newNode->data = data;newNode->next = NULL;return newNode;
}// 在链表末尾添加新节点
void append(LinkedList* head, int data) {if (*head == NULL) {*head = createNode(data);}else {Node* lastNode = *head;while (lastNode->next != NULL) {lastNode = lastNode->next;}lastNode->next = createNode(data);}
}// 打印链表
void printList(LinkedList head) {while (head != NULL) {printf("%d ", head->data);head = head->next;}printf("\n");
}LinkedList findNodeK(Node* head1, int k)
{if (head1 == NULL){return NULL;}int length = 0;Node* tail = head1;while (tail != NULL){tail = tail->next;length++;}if (length <= k){return head1;}Node* cur = head1;int i = length - k;while(i != 0){cur = cur->next;i--;}return cur;
}int main() {LinkedList head1 = NULL;append(&head1, 1);append(&head1, 2);append(&head1, 3);append(&head1, 4);append(&head1, 5);append(&head1, 6);printf("Original List1: ");printList(head1);LinkedList head = findNodeK(head1, 4);printf("findNodeK List: ");printList(head);system("pause");return 0;
}

参考:https://blog.csdn.net/weixin_53161762/article/details/137611306?spm=1001.2014.3001.5501

http://www.lryc.cn/news/337681.html

相关文章:

  • 在一台恢复测试机器上验证oracle备份有效性
  • Harmony鸿蒙南向驱动开发-MIPI CSI
  • 最优算法100例之43-包含min函数的栈
  • 什么是One-Class SVM
  • 【Ubuntu】远程连接乌班图的方式-命令行界面、图形界面
  • Ubuntu无网络标识的解决方法
  • 基于springboot实现课程答疑管理系统项目【项目源码+论文说明】
  • 【JVM】面试题汇总
  • 趣谈 Rust 的 Copy trait 和 Clone trait
  • 02 - Git 之命令 +
  • 每日一练(力扣)
  • JWT详解及实战教程
  • vue通过echarts实现数据可视化
  • react17中使用setState导致了死循环
  • 2024年P气瓶充装证模拟考试题库及P气瓶充装理论考试试题
  • Python学习笔记(一)
  • 记一次http访问超时服务器端调试
  • C/C++内存泄漏及检测
  • 跟TED演讲学英文:Why AI will spark exponential economic growth by Cathie Wood
  • 常用组合逻辑电路模块(4):数值比较器
  • 实时时钟模块RX8901CE具有数字温度补偿功能,助力工业设备实现精准控制
  • Acrobat Pro DC 2023 for mac直装激活版 pdf编辑处理工具
  • 3D应用模型信创系统实时渲染有什么要求?
  • Flutter之TabBar篇
  • VRRP(虚拟路由冗余协议)详解
  • 【数据结构】04串
  • LAMMPS如何识别多孔结构的孔隙及其大小
  • JavaScript ECMAScript标准的与时俱进:从ES6至ES14的革新之路与关键技术特性剖析
  • 竞赛课第六周(树状数组的应用)
  • SpringCloud Alibaba Sentinel 实现熔断功能