c++链表

#include <iostream>
#include <string>
using namespace std;

//结构
struct men
{
	int age;
	men *next;
};

//生成有序链表
void insertM(men *&head, int num)
{
	men *s, *q;//定义指针
	s = new men;//定义堆内存
	s->age = num;//新结点
	s->next = NULL;//新结点
	if (head == NULL)//如果没有指向
	{
		head = s;//直接指向并返回
		return;
	}
	if (head->next == NULL)//如果只有一项
	{
		if (head->age > num)//应该放在前面
		{
			s->next = head;//新结点的next指向第一项
			head = s;//头指针指向新结点
		}
		else//应该放在第二项
		{
			head->next = s;//头指针的next指向新结点
		}
		return;
	}

	q = head;//跟踪指针指向头指针 开始遍历
	while (q->next != NULL)//当还有下一结点的时候
	{
		if (q->next->age >= num)//下一结点的值比较大
		{
			s->next = q->next;//新结点的next指向下一结点
			q->next = s;//跟踪指针的next指向新结点
			return;
		}
		if (q->next->next == NULL)//下一结点的next指向空 即没有下下结点了
		{
			q->next->next = s;//把新结点放在链表最后
			return;
		}
		q = q->next;//遍历递增
	}
}
void showM(const men *head)
{
	cout << "Now mens club include:" << endl;
	while (head)
	{
		cout << head->age << '\t';
		head = head->next;
	}
	cout << endl;
}

int main()
{
	men *head = NULL;//初始化头指针
	int num;
	cin >> num;
	while (num != 0)
	{
		insertM(head, num);
		cin >> num;
	}
	showM(head);
	getchar();
	return 0;
}

  

posted @ 2018-01-19 09:31  花兮  阅读(100)  评论(0编辑  收藏  举报