题目:定义一个函数,输入一个链表的头节点,反转该链表并输出反转链表的头节点。
#include <iostream>
using namespace std;
typedef struct listnode
{
int val;
struct listnode* next;
}ListNode;
void creatList(ListNode** head)
{
int num;
cin >> num;
ListNode* tail = nullptr;
while (num != -1)
{
ListNode* node = new ListNode;
node->val = num;
node->next = nullptr;
if (*head == nullptr)
{
*head = node;
tail = node;
}
else
{
tail->next = node;
tail = node;
}
cin >> num;
}
}
void reverseList(ListNode** head)
{
if (*head == nullptr || (*head)->next == nullptr)
return;
ListNode* rtail, *rsecond, *rhead;
rtail = *head;
rsecond = (*head)->next;
rhead = (*head)->next;
rtail->next = nullptr;
while (rhead->next != nullptr)
{
rhead = rhead->next;
rsecond->next = rtail;
rtail = rsecond;
rsecond = rhead;
}
rhead->next = rtail;
*head = rhead;
}
int main()
{
ListNode* head = nullptr;
creatList(&head);
reverseList(&head);
}