35. Reverse Linked List

元气小坏坏 提交于 2020-01-29 02:41:25

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;
        
    }
};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!