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

实现链表逆序

2013年09月14日 ⁄ 综合 ⁄ 共 553字 ⁄ 字号 评论关闭

今天听课的时候突然提到一个问题,如何把链表逆序,考虑一下,简单指针操作即可。 

#include<iostream>
using namespace std;

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

class LinkedList
{
public:
	LinkedList()
	{
		first = new node;
		int i = 1;
		node* p = first;
		while(i < 10)
		{
			node* q = new node;
			q->data = i;
			q->next = NULL;
			p->next = q;
			p = p->next;
			i++;
		}
	};
	void putOut()
	{
		node* p = first->next;
		while(p != NULL)
		{
			cout << p->data << endl;
			p = p->next;
		}
	};
	void reverse()
	{
		node* p = NULL;
		node* q = first->next;
		while(q != NULL){
			node *m = q->next;
			q->next = p;
			if(m == NULL)
			{
				first->next = q;
				break;
			}
			else
			{
				p = q;
				q = m;
			}
		}
	}
		
	
private:
	node* first;
};

int main()
{
	LinkedList a;
	a.putOut();
	a.reverse();
	a.putOut();
	return 0;
}

抱歉!评论已关闭.