输出链表倒数第K个节点

来源:互联网 发布:网络教育文凭价格 编辑:程序博客网 时间:2024/06/16 00:16

题目:

输入一个链表,输出该链表倒数第K个节点。

方法1

想获取第K个节点,只要知道整个链表的长度n即可,K个节点为:从链表头起第 n-k+1个节点。此算法的缺陷是需要遍历2次链表。

方法2: 

设置2个指针,再设置一个步长为:k - 1,即第一个指针指向的位置和第二个指针相差 k -1个节点。当第二个节点走到最后一个节点的时候,第一个指针刚好就是第K个节点。
优点: 只遍历一次链表。

延伸:

输出链表的中间节点。

代码:
#include <stdio.h>#include <stdlib.h>//声明节点,类型重命名typedef struct node{int data;struct node* next;}Node;//依次显示链表数据void show(Node* phead){while(phead){printf("%d\t", phead->data);phead = phead->next;}printf("\n");}
//创建链表Node* create(Node* phead, int d){Node* tmp = malloc(sizeof(Node));tmp->data = d;tmp->next = NULL;Node* find = phead;if(phead == NULL)phead = tmp;else {while(find->next != NULL)find = find->next;find->next = tmp;}return phead;}//方法一Node* find_k(Node* phead, int k){int count = 0, i = 0;Node* find = phead;if(phead == NULL)return NULL;while(find->next != NULL){count++;find = find->next;}if(k > count){printf("K is too big. \n");exit(1);}find = phead;while(i < count-k+1){find = find->next;i++;}return find;}//方法二Node* find_k2(Node* phead, int k){int step = k - 1;Node* first = phead;Node* second = phead;if(phead == NULL)return NULL;while(step){second = second->next;step--;}while(second->next != NULL){first = first->next;second = second->next;}return first;}int main(){Node* head = NULL;head = create(head, 11);head = create(head, 22);head = create(head, 33);head = create(head, 44);head = create(head, 55);head = create(head, 66);head = create(head, 77);show(head);Node* tmp = find_k(head, 3);//查找倒数第三个节点if(tmp == NULL){printf("the list is NULL. \n");exit(1);}printf("tmp->data: %d\n", tmp->data);return 0;}

结果:



0 0
原创粉丝点击