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

单链表的操作

2013年08月30日 ⁄ 综合 ⁄ 共 662字 ⁄ 字号 评论关闭

 

#include "stdafx.h"
#include <iostream>
using namespace std;

struct Node 
{
	int element;
	Node *pNext;
	Node(int ele = 0, Node *next = NULL)
		:element(ele), pNext(next){}
};
//创建单链表
Node *CreateList(int n)
{
	Node *head = new Node;
	Node *cur = head;
	Node *temp = NULL;
	for (int i = 0; i < n; ++i)
	{
		temp = new Node(i + 1);
		cur->pNext = temp;
		cur = temp;
	}
	return head->pNext;
}
//输出单链表
void Print(Node *head)
{
	while (head != NULL)
	{
		cout<<head->element<<" ";
		head = head->pNext;
	}
	cout<<endl;
}
//反转单链表
void ReverseList(Node *&head)
{
	if (head == NULL)
		return;
	Node *p = NULL;
	Node *cur = head;
	Node *q = NULL;

	while (cur->pNext != NULL)
	{
		q = cur->pNext;
		cur->pNext = p;
		p = cur;
		cur = q;
	}

	cur->pNext = p;
	head = cur;
}
int main()
{
	Node *head = CreateList(7);
	Print(head);

	ReverseList(head);
	Print(head);
}

抱歉!评论已关闭.