35. Reverse Linked List
Description:
Reverse a linked list.
Example
Example 1:
Input: 1->2->3->null
Output: 3->2->1->null
Example 2:
Input: 1->2->3->4->null
Output: 4->3->2->1->null
Challenge
Reverse it in-place and in one-pass
Main Idea:
Fundamental linked list problem.
Code:
/**
* Definition of singly-linked-list:
*
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: n
* @return: The new head of reversed linked list.
*/
ListNode * reverse(ListNode * head) {
// write your code here
if(head == nullptr || head->next == nullptr){
return head;
}
ListNode* p1 = head;
ListNode *p2 = head->next, *p3;
p1->next = nullptr;
while(p2){
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
return p1;
}
};
来源:CSDN
作者:Zahb44856
链接:https://blog.csdn.net/Zahb44856/article/details/104054487