加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 20:05:27 所属栏目:百科 来源:网络整理
导读:以前写的都是生成的都是逆序的,所以不需要头结点。如果生成正序链表则需要头结点来完成。 #include iostream#include stringusing namespace std;class MList{struct LNode{int elem;LNode *next;};//利用一个头结点,一个头指针和一个尾指针实现正序插入的

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

#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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读