leetcode206 Reverse Linked List(反转链表)

xiaoxiao2025-09-01  7

题目链接 https://leetcode.com/problems/reverse-linked-list/ 知识点: 考察链表指针相关知识 思路: 用pre、cur、next三个指针操作。反转完毕后返回此时的头结点指针pre即可 代码:

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* pre = NULL; ListNode* cur = head; while(cur != NULL) { ListNode* next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } };

AC代码加测试如下:

#include <bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* createLinkedList(int arr[], int n) { if(n == 0) return NULL; ListNode* head = new ListNode(arr[0]); ListNode* curNode = head; for(int i=1; i<n; i++) { curNode->next = new ListNode(arr[i]); curNode = curNode->next; } return head; } void printLinkedList(ListNode* head) { ListNode* curNode = head; while(curNode!=NULL) { cout<<curNode->val<<" -> "; curNode = curNode->next; } cout<<"NULL"<<endl; } void deleteLinkedList(ListNode* head) { ListNode* curNode = head; while(curNode!=NULL) { ListNode* delNode = curNode; curNode = curNode->next; delete delNode; } } class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* pre = NULL; ListNode* cur = head; while(cur != NULL) { ListNode* next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } }; int main() { int arr[]= {1,2,3,4,5}; int n = sizeof(arr)/sizeof(int); ListNode* head = createLinkedList(arr,n); printLinkedList(head); ListNode* head1 = Solution().reverseList(head); printLinkedList(head1); deleteLinkedList(head1); return 0; }

转载请注明原文地址: https://www.6miu.com/read-5035571.html

最新回复(0)