剑指Offer之 - 反转链表

来源:互联网 发布:js获取选中的一行数据 编辑:程序博客网 时间:2024/06/11 04:12

题目:

输入一个链表头结点,反转该链表,并输出反转后链表的头结点。

思路:

……

代码:

#include <iostream>using namespace std;struct ListNode {int m_nKey;ListNode *m_pNext;ListNode(){}ListNode(int x):m_nKey(x),m_pNext(NULL){}};//功能:翻转链表。p1 = NULL , p2 = pHead , p3 = p2->m_pNextListNode * ReverseList(ListNode * pHead){ListNode *p1 = NULL , *p2 = pHead;if(pHead == NULL || pHead->m_pNext == NULL)return pHead;while(p2){ListNode * pNext = p2->m_pNext;if(pNext == NULL)pHead = p2;p2->m_pNext = p1;p1 = p2;p2 = pNext;}return pHead;}int main(){ListNode *p1 = new ListNode(1);  ListNode *p2 = new ListNode(2);  ListNode *p3 = new ListNode(3);  ListNode *p4 = new ListNode(4);  ListNode *p5 = new ListNode(5);  ListNode *p6 = new ListNode(6);  p1->m_pNext = p2;  p2->m_pNext = p3;  p3->m_pNext = p4;  p4->m_pNext = p5;  p5->m_pNext = p6; ListNode *p = ReverseList(p1);while(p){cout<<p->m_nKey<<" ";p = p->m_pNext;}cout<<endl;return 0;}


0 0