现在的位置: 首页 > 综合 > 正文

链表中倒数第k个结点

2014年09月05日 ⁄ 综合 ⁄ 共 1367字 ⁄ 字号 评论关闭

输入一个链表,输出该链表中倒数第k个结点为了符合大多数人的习惯,从1开始计数,即链表的尾结点是倒数第一个结点,例如一个链表有6个结点,从头结点开始它们依次是1、2、3、4、5、6,这个链表的倒数第3个结点是值为4的结点。

#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;

struct Node
{
	int data;
	struct Node* next;
};

struct Node* create_list(int len)
{	
	if (len <= 0)
		return NULL;

	struct Node* head;
	struct Node* tmp;
	struct Node* pre;
	for (int i=0; i<len; i++)
	{
		if (i == 0)
		{
			head = tmp = new struct Node;
			cin >> tmp->data;
			tmp->next = NULL;
			pre = tmp;
			continue;
		}
		tmp = new struct Node;
		cin >> tmp->data;
		tmp->next = NULL;
		pre->next = tmp;
		pre = tmp;
	}

	return head;
}

void visit(const struct Node *head)
{
	if (head == NULL)
		return;
	const struct Node *tmp;
	tmp = head;
	while (tmp)
	{
		cout << tmp->data << endl;
		tmp = tmp->next;
	}
}

void free_list(struct Node *head)
{
	if (head == NULL)
		return;
	struct Node *tmp;
	while (head)
	{
		tmp = head;
		head = head->next;
		delete tmp;
	}
}


enum Status{kValid, kInvalid};
int  kStatus = kValid;
/*
*如果没有倒数第k个结点,那么返回0,并设置kInvalid标志.
*/
int find_k(const struct Node *head, int k)
{
	if (head == NULL || k <= 0)
	{
		kStatus = kInvalid;
		return 0;
	}
	
	int times = 0;	
	const struct Node *tmp = head;
	const struct Node *last = head;
	while (tmp)
	{
		times++;
		if (times > k)
		{
			last = last->next;
		}
		tmp = tmp->next;
	}
	if (times < k)
	{
		kStatus = kInvalid;
		return 0;
	}
	return last->data;
}

int main()
{
	struct Node *head = create_list(6);
	visit(head);
	
	int r = find_k(head, 3);
	if (r == 0 && kStatus == kInvalid)
		cout << "k非法输入" << endl;
	else
		cout << "倒数第3个结点值: " << r << endl;
	
	r = find_k(head, 7);
	if (r == 0 && kStatus == kInvalid)
		cout << "k非法输入" << endl;
	else
		cout << "倒数第7个结点: " << r << endl; 
	
	free_list(head);	
	return 0;
}

抱歉!评论已关闭.