15、反转链表
输入一个链表,反转链表后,输出新链表的表头。
示例1
输入
{1,2,3}
返回值
{3,2,1}
很好的解答
https://blog.csdn.net/qq_42351880/article/details/88637387
1、头插法 很经典的做法啊
struct ListNode { int val; struct ListNode* next; ListNode(int x) : val(x), next(NULL) { } }; ListNode* ReverseList(ListNode* pHead) { struct ListNode* Head = NULL; struct ListNode* node = (ListNode*)malloc(sizeof(struct ListNode)); while (pHead != nullptr) { node = pHead; pHead = pHead->next; node->next = Head; Head = node; } return Head; } void test02() { ListNode* head = (ListNode*)malloc(sizeof(ListNode)); head->val = 1; ListNode* node1 = (ListNode*)malloc(sizeof(ListNode)); node1->val = 2; ListNode* node2 = (ListNode*)malloc(sizeof(ListNode)); node2->val = 3; ListNode* node3 = (ListNode*)malloc(sizeof(ListNode)); node3->val = 4; head->next = node1; node1->next = node2; node2->next = node3; node3->next = nullptr; auto node = ReverseList(head); while(node!=nullptr){ cout << node->val << endl; node = node->next; } }