链表的正序生成、插入和倒置

以前写的都是生成的都是逆序的,所以不需要头结点。如果生成正序链表则需要头结点来完成。

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

class MList{
	struct LNode{
		int elem;
		LNode *next;
	};
	//利用一个头结点,一个头指针和一个尾指针实现正序插入的链表
	//head值初始化一次即可(因为总指向头所以不能变化,需要一个头结点
	//达到这个效果)。tail在每次插入时候调整。
	//也可以使用if……else结构来处理
	LNode header;
	LNode *head;
	LNode *tail;
public:
	MList(){
		head=&header;
		tail=&header;
	}
	void add(int value);
	void reve();
	void display();
};

void MList::add(int value){
	LNode *p=new LNode();
	p->elem=value;
	p->next=NULL;
	tail->next=p;
	tail=p;
}

void MList::display(){
	LNode *p=head->next;
	while (p != NULL)
	{
		cout << p->elem << endl;
		p=p->next;
	}
}

void MList::reve(){
	//这里的调整技巧
	LNode *h = head->next;
	LNode *tmp1 = head->next;
	LNode *tmp2 = tmp1->next;
	while (tmp2 != NULL)
	{
		head->next=tmp2;
		tmp2=tmp2->next;
		head->next->next=tmp1;
		tmp1=head->next;
	}
	tail=h;
	tail->next=NULL;
}

int main(){
	MList mylist;
	mylist.add(1);
	mylist.add(2);
	mylist.add(3);
	mylist.display();//1 2 3
	mylist.reve();
	mylist.add(4);
	mylist.reve();
	mylist.display();//4 1 2 3 
	return 0;
}

相关文章

什么是设计模式一套被反复使用、多数人知晓的、经过分类编目...
单一职责原则定义(Single Responsibility Principle,SRP)...
动态代理和CGLib代理分不清吗,看看这篇文章,写的非常好,强...
适配器模式将一个类的接口转换成客户期望的另一个接口,使得...
策略模式定义了一系列算法族,并封装在类中,它们之间可以互...
设计模式讲的是如何编写可扩展、可维护、可读的高质量代码,...