首页 > 代码库 > 给定一个链表的头指针,要求只遍历一次,将单链表中的元素顺序反转过来

给定一个链表的头指针,要求只遍历一次,将单链表中的元素顺序反转过来

经典题目,代码如下:

 1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 struct ListNode { 5     int m_iData; 6     ListNode* m_pNext; 7 }; 8 ListNode* Reverse(ListNode* in_pListNode) { 9     if(in_pListNode == NULL) {10         return NULL;11     }else if(in_pListNode->m_pNext == NULL) {12         return in_pListNode;13     }14     ListNode* t_pFirst = in_pListNode->m_pNext;15     ListNode* t_pSecond = in_pListNode->m_pNext->m_pNext;16     in_pListNode->m_pNext = NULL;17     while(t_pFirst != NULL && t_pSecond != NULL) {18         t_pFirst->m_pNext = in_pListNode;19         in_pListNode = t_pFirst;20         t_pFirst = t_pSecond;21         t_pSecond = t_pSecond->m_pNext;22     }23     t_pFirst->m_pNext = in_pListNode;24     return t_pFirst;25 }26 27 int main() {28     ListNode* t_iListNode = new ListNode();29     ListNode* t_iListNodeHead = t_iListNode;30     for(int i = 1; i < 10; i ++) {31         t_iListNode->m_iData =http://www.mamicode.com/ i;32         ListNode* t_iListNodeNext = new ListNode();33         t_iListNode->m_pNext = t_iListNodeNext;34         t_iListNode = t_iListNodeNext;35     }36     t_iListNode->m_iData = http://www.mamicode.com/10;37     ListNode* t_iTempListNode =t_iListNodeHead;38     cout << "链表翻转前:" ;39     while(t_iTempListNode != NULL) {40         cout << t_iTempListNode->m_iData << " ";41         t_iTempListNode = t_iTempListNode->m_pNext;42     }43     cout << endl;44     45     t_iTempListNode = Reverse(t_iListNodeHead);46     47     cout << "链表翻转后:" ;48     while(t_iTempListNode != NULL) {49         cout << t_iTempListNode->m_iData << " ";50         t_iTempListNode = t_iTempListNode->m_pNext;51     }52     cout << endl;53       system("pause"); 54       return 0;55      56      57 }

 

给定一个链表的头指针,要求只遍历一次,将单链表中的元素顺序反转过来