反转链表

来源:互联网 发布:photoshop mac版下载 编辑:程序博客网 时间:2024/06/08 10:28

注意这里反转时候,要把头指针指向的节点的next域设为NULL,才可以从后面往前输出时候能截止。

#include <iostream>#include <stdio.h>#include <map>#include <string>#include <sstream>#include <cstdlib>using namespace std;typedef struct _LinkNode{  int data;  struct _LinkNode *next;}LinkNode,*PLinkNode;PLinkNode InitLinkList(){PLinkNode head,cur,front;int temp;int time=0;while(cin>>temp&&temp!=0){time++;cur=(PLinkNode )malloc(sizeof(LinkNode));cur->data=temp;cur->next=NULL;if(time==1)head=front=cur;else{front->next=cur;front=cur;}}return head;  }void TraverseLinkList(PLinkNode head){PLinkNode p=head;  while(p)  {  cout<<p->data<<endl;  p=p->next;  }}void ReverseLinkList(PLinkNode head){PLinkNode p1,p2,p3;p1=p2=head;p3=p1->next;p1->next=NULL;int time=0;while(p3){p2=p3;p3=p3->next;p2->next=p1;p1=p2;    }TraverseLinkList(p2);}int main(){PLinkNode head=InitLinkList();TraverseLinkList(head);ReverseLinkList(head);return 0;}


0 0
原创粉丝点击