题目:定义一个函数,输入一个链表的头结点,反转该链表并输出翻转后该链表的头结点。
#include <iostream>
using namespace std;
struct ListNode {
int m_nKey;
ListNode *m_pNext;
};
ListNode *CreateList() {
int a;
cin >> a;
ListNode *head;
head = NULL;
if (a != -1) {
head = new ListNode;
head->m_nKey = a;
head->m_pNext = CreateList();
}
return head;
}
ListNode *ReverseList(ListNode *pHead) {
if (pHead == NULL || pHead->m_pNext == NULL)
return pHead;
ListNode *pPre = NULL;
ListNode *pCur = pHead;
ListNode *pNext = pHead->m_pNext;
while (pCur != NULL) {
pCur->m_pNext = pPre;
pPre = pCur;
pCur = pNext;
if (pNext != NULL)
pNext = pNext->m_pNext;
}
cout << pPre->m_nKey << endl;
return pPre;
}
int main() {
ListNode *head = CreateList();
head = ReverseList(head);
while (head != NULL) {
cout << head->m_nKey << " ";
head = head->m_pNext;
}
cout << endl;
return 0;
}