以前写的都是生成的都是逆序的,所以不需要头结点。如果生成正序链表则需要头结点来完成。
#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; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。