链表压缩问题

输入一个非严格递增整数数列(以-1结束),第一行依次输出每一个数的个数,第二行输出压缩后的不含重复数的链表。

测试样例:

1 -1

1 1 -1

1 1 2 3 3 3 6 -1

1 2 3 6 6 6 6 -1

1 2 3 100 200 1000 -1

#include <iostream>
using namespace std;
struct Node
{
	int data;
	Node *next;
};
Node *input();
void output(Node *);
void count(Node *);
Node *shorten(Node *);
int main()
{
	Node *head = NULL;
	head = input();
	count(head);
	Node *phead = shorten(head);
	output(phead);
	return 0;
}

Node *input()
{
	Node *head = NULL, *tail = NULL;
	int x;
	cin >> x;
	while (x != -1)
	{
		Node *p = new Node;
		p->data = x;
		p->next = NULL;
		if (head == NULL)
			head = tail = p;
		else
		{
			tail->next = p;
			tail = p;
		}
		cin >> x;
	}
	return head;
}

void output(Node *head)
{
	cout << endl;
	for (Node *p = head; p != NULL; p = p->next)
		cout << p->data << " ";
	cout << endl;
}

void count(Node *head)
{
	if (head == NULL)
		return;
	else
	{
		Node *s = head, *t = head->next;
		int cnt = 1;
		while (t != NULL && s->data == t->data)
		{
			cnt++;
			s = s->next;
			t = t->next;
		}
		cout << cnt << ' ';
		/*下面考虑循环退出条件为s->data != t->data的情况,当然链表到头就无话可说了,只能结束*/
		if (t != NULL)
		{
			s = s->next;
			t = t->next;
			count(s);
		}
		//纯粹是因为不等,毕竟还没有到结束位置,那么就开始下一个值的计数吧
	}
}
Node *shorten(Node *s)
{
	if (s == NULL)
		return NULL;
	Node *p = new Node;
	p->data = s->data;
	p->next = NULL;
	Node *head = p, *tail = p;
	Node *t = s->next;//t是第二个结点
	while (t != NULL)
	{
		if (t->data != s->data)
		{
			Node *p = new Node;
			p->data = t->data;
			p->next = NULL;
			tail->next = p;
			tail = p;
		}
		//添加结点当且仅当值不同时
		t = t->next;
		s = s->next;
	}
	return head;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值