数据结构——算法之(004)(输入一个单向链表,输出该链表中倒数第k个结点)

来源:互联网 发布:mac卸载office2016 编辑:程序博客网 时间:2024/06/17 02:52

【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:Mr_chenping@163.com】

题目:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。
链表结点定义如下:  

typedef struct _list_node{int        key;struct _list_node  *next;}list_node;

题目分析:

解法一、先计算链表中总节点个数N,然后循环遍历N-k+1次(排除带头结点的情况)。

解法二、两个指针p,q同时指向头结点,让一个指针p先走k步,然后两个指针同时循环遍历链表,当p到达尾节点的时候,返回q即可。

算法实现:(解法二)

#include <stdio.h>#include <stdlib.h>typedef struct _list_node{int        key;struct _list_node  *next;}list_node;void *list_insert(list_node *head, int key){list_node *p = head;while(p->next != NULL)p = p->next;list_node *node = calloc(1, sizeof(list_node));node->key = key;node->next = NULL;p->next = node;}list_node * list_return_node_by_key(list_node *head, int index){list_node * re = head->next;list_node * p = head;/*让返回节点指针先走index步*/int i=0;for(; i<index; ++i)p = p->next;/*遍历链表,当@l为NULL的时候@re刚好指向倒数第K个节点*/while(p->next != NULL){p = p->next;re = re->next;}return re;}int main(int argc, char *argv[]){list_node *head = calloc(1, sizeof(list_node));head->key = 0;head->next = NULL;list_insert(head, 1);list_insert(head, 2);list_insert(head, 3);list_insert(head, 4);list_insert(head, 5);list_node *node = list_return_node_by_key(head, 3);printf("node->key = %d\n", node->key);return 0;}


0 0