Reverse Linked List
Total Accepted: 1726 Total Submissions: 4378My Submissions
Question Solution
Reverse a singly linked list.
Hide Tags
Have you met this question in a real interview?
Yes
No
这道题比较简单,主要是给链表反序,所以可以设置三个指针,ptr0,ptr1指向要交换的两个结点,ptr2在交换之前先指向ptr1的下一个结点,
这样好为下一次交换做准备,即再往后移就可以了,直到末尾
#include<iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* reverseList(ListNode* head) { if(head==NULL||head->next==NULL) return head; ListNode* ptr0=head; ListNode* ptr1=head->next; ListNode* ptr2; ptr0->next=NULL; while(1) { ptr2=ptr1->next; ptr1->next=ptr0; if(ptr2==NULL) break; ptr0=ptr1; ptr1=ptr2; } return ptr1; } int main() { }
时间: 2024-12-14 21:19:00