- #include <iostream>
- using namespace std;
- struct list
- {
- int data;
- list *next;
- };
- list *head=new list;
- list *tail=head;
- void add(int n)
- {
- list *p=new list;
- memset(p,0,sizeof(list));
- tail->next=p;
- p->data=n;
- tail=p;
- }
- void print()
- {
- list *p=head->next;
- while(p)
- {
- cout<<p->data<<endl;
- p=p->next;
- }
- }
- void printtail()
- {
- list *p=tail;
- while(p->next)
- {
- cout<<p->data<<endl;
- p=p->next;
- }
- }
- void nizhi1()
- {
- int sum=0;
- list *p=head->next;
- while(p){p=p->next;sum++;}
- for (int i=0;i<sum/2;i++)
- {
- p=head->next;
- for (int j=0;j<i;j++ ) //j<i
- {
- p=p->next;
- }
- cout<<"l:"<<p->data<<endl;
- list *r=head->next;
- for (int jj=0;jj<sum-i-1;jj++) //-1
- {
- r=r->next;
- }
- cout<<"r:"<<r->data<<endl;
- int temp=p->data;
- p->data=r->data;
- r->data=temp;
- }
- }
- void nizhi2()
- {
- int sum =0; //新建一个动态数组存放链表地址 address[0]存放head地址
- list *p=head;
- while(p) {sum++;p=p->next;}
- list **address=new list *[sum];
- memset(address,0,sizeof(address));
- p=head;
- for (int i=0;i<sum;i++)
- {
- address[i]=p;
- p=p->next;
- }
- cout<<"sum:"<<sum<<endl;
- p=head;
- p->next=0;
- for (i=1;i<sum;i++)
- {
- address[i]->next=address[i-1];
- }
- delete [] address;
- }
- int main()
- {
- add(1);
- add(2);
- add(3);
- add(4);
- add(5);
- print();
- cout<<endl;
- nizhi1();
- print();
- nizhi2();
- cout<<endl;
- printtail();
- return 0;
- }