剑指offer-面试题16.反转链表

来源:互联网 发布:无锡胡埭加工中心编程 编辑:程序博客网 时间:2024/06/04 07:54

题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后的头结点

链表结点定义如下:

1 struct ListNode2 {3     int    m_nKey;4     ListNode* m_pNext;5 }

 

其实反转链表主要是链表指针的操作,一定要很清楚才行。其实在面试题5,从尾到头打印链表的第一种方式已经实现了这种方式:

 

这里在梳理下反转链表的过程:

比如链表:1->2->3->4->5->6

1.定义三个指针p1,p2,p3

2.p1指向1,p2指向2,p3指向3

3.p2->next=p1;然后p1=p2,p3=p2

4.这时1<-2  3->4->5->6 p1指向2,p2指向3,p3指向4

5.重复第4步(p2->next=p1,p1=p2,p3=p2,此时1<-2<-3 4->5->6 依次类推)

6.结束条件为p2==NULL,最后将头结点的next指向NULL即可

 

实现如下:

复制代码
 1 #include <iostream> 2 using namespace std; 3  4 struct ListNode 5 { 6     int data; 7     struct ListNode *next; 8 }; 9 10 struct ListNode* CreateList()11 {12     struct ListNode* Head,*p;13     Head=(struct ListNode*)malloc(sizeof(ListNode));14     Head->data=0;15     Head->next=NULL;16     p=Head;17 18     cout<<"Create List....(0-exit!)"<<endl;19     while(true)20     {21         int Data;22         cin>>Data;23         if(Data!=0)24         {25             struct ListNode* NewNode;26             NewNode=(struct ListNode*)malloc(sizeof(ListNode));27             NewNode->data=Data;28             NewNode->next=NULL;29             p->next=NewNode;30             p=p->next;31         }32         else33         {34             break;35         }36     }37 38     return Head->next;39 }40 41 void PrintList(struct ListNode* Head)42 {43     cout<<"The List is: ";44 45     struct ListNode *p;46     p=Head;47     while(p!=NULL)48     {49         cout<<p->data<<" ";50         p=p->next;51     }52     cout<<endl;53 }54 55 struct ListNode* ReversePrint(struct ListNode* Head)56 {57     struct ListNode *p1,*p2,*p3;58 59     p1=Head;60     p2=p1->next;61 62     while(p2!=NULL)63     {64         p3=p2->next;65         p2->next=p1;66         p1=p2;67         p2=p3;68     }69 70     Head->next=NULL;71     return p1;72 }73 74 int main()75 {76     ListNode *Head,*NewHead;77     Head=CreateList();78     PrintList(Head);79     NewHead=ReversePrint(Head);80 81     cout<<endl<<"The Reverse List is:"<<endl;82     PrintList(NewHead);83     return 0;84 }
复制代码

 

运行截图:


0 0
原创粉丝点击