算法—查找倒数第k个链表的值
代码:
link.h
#pragma once
#define elemType int
#include<stdlib.h>
typedef struct link {elemType data;struct link * next;
}link;
bool initLink(link* &Link) {//初始化链表Link = (link*)malloc(sizeof(link));Link->next = NULL;if (!Link) {return false;}return true;
}
int getLinkElem(link* &Link,int i) {//获取链表的第i个元素link* p = Link;int j = 0;while (p&&j < i) {p = p->next;j++;}if (j >= i || !p) {return -1;}int v = p->data;return v;
}
bool LinkTailInsert(link* &Link, int i,int e) {//链表的第i个位置插入元素link* p = Link;link*s = (link*)malloc(sizeof(link));s->data = e;int j = 0;while (p&&j < i - 1) {p = p->next;j++;}if (!p || j > i - 1) {return false;}s->next = p->next;p->next = s;return true;
}
bool deleteLinkElem(link* &Link,int i) {//删除链表的第i个元素int j = 0;link* p = Link,*q;while (p&&j < i - 1) {p = p->next;j++;}if (!p || j > i - 1) {return false;}q = p->next;p->next = q->next;delete q;return true;
}
void printLink(link* Link) {//遍历链表link *p = Link->next;while (p) {printf("%d ", p->data);p = p->next;}printf("\n");
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include"link.h"
int checkTheLastElem(link* Link, int k) {//查找链表中倒数第k个元素link *p = Link;//带头结点(头指针)link *q = Link;int count = 0;while (p) {if (count < k) {count++;}else {q = q->next;//q指针只有k>}p = p->next;//p指针一直移动}if (count < k) {printf("查找倒数第%d个元素失败\n",k);return 0;}else {printf("查找倒数第%d个元素成功!为%d\n", k,q->data);return 1;}
}
int main() {link* Link;initLink(Link);int i = 0;while (i<3) {int v;scanf_s("%d", &v);LinkTailInsert(Link, 1,v);i++;}printf("遍历链表:");printLink(Link);//遍历checkTheLastElem(Link, 1);//查找倒数第一个元素printf("\n");system("pause");return 0;
}