[剑指offer][面试题16]反转链表
2013-10-12 15:43
549 查看
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
#include <iostream> using namespace std; struct Node{ int m_Data; Node *m_pNext; }; Node* reverseList(Node *pHead) { if (pHead==NULL){ return NULL; } if (pHead->m_pNext==NULL){ return pHead; } Node *pPrev = pHead; Node *pCurr = pHead->m_pNext; Node *pNext = NULL; pPrev->m_pNext = NULL; while (pCurr){ pNext = pCurr->m_pNext; pCurr->m_pNext = pPrev; pPrev = pCurr; pCurr = pNext; } return pPrev; } void printList(Node *pHead) { bool bEmpty = true; while (pHead){ bEmpty = false; cout<<pHead->m_Data<<"->"; pHead = pHead->m_pNext; } if (!bEmpty){ cout<<"NULL"<<endl; } } int main() { Node nodeA5 = {1, NULL}; Node nodeA4 = {2, &nodeA5}; Node nodeA3 = {3, &nodeA4}; Node nodeA2 = {4, &nodeA3}; Node nodeA1 = {5, &nodeA2}; Node nodeA0 = {6, &nodeA1}; Node *pHeadA = &nodeA0; cout<<"Linked List: "<<endl; printList(pHeadA); pHeadA = reverseList(pHeadA); cout<<"Reversed List: "<<endl; printList(pHeadA); }
相关文章推荐
- 剑指offer--面试题16: 反转链表
- 【剑指Offer】面试题16:反转链表
- 【剑指offer】3.4代码的鲁棒性——面试题16:反转链表
- 剑指offer-面试题 16:反转链表
- 【剑指offer 面试题16】反转链表
- 剑指offer 面试题16:反转链表(Leetcode 206: Reverse Linked List) 题解
- 剑指Offer面试题16(Java版):反转链表
- 【面试题】剑指Offer-16-反转链表
- 【剑指offer】面试题16:反转链表
- 剑指Offer:面试题16——反转链表(java实现)
- 剑指offer面试题16:反转链表
- 剑指Offer----面试题16:反转链表
- 【剑指Offer学习】【面试题16 :反转链表】
- 【剑指offer】面试题16:反转链表
- 剑指offer之面试题16 :反转链表
- 剑指Offer之面试题16:反转链表
- 剑指offer:面试题16 反转链表
- 剑指offer——面试题16:反转链表
- 【剑指offer】面试题16:反转链表
- 剑指offer面试题16 反转链表