35. 翻转链表(reverse-linked-list)(c++)----lintcode面试题之链表

(一)题目要求:

翻转一个链表

(二)示例:

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

(三)题解:

方法一:

/**
 * Definition of ListNode
 * 
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 * 
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */

 //方法一:只有一个结点时无操作
 //p_front 指向头结点  p_insert指向头结点的下一个结点
 //下一个结点更新
 //p_insert插入链表头
 //p_insert置为下一个结点

class Solution {
public:
    /*
     * @param head: n
     * @return: The new head of reversed linked list.
     */
    ListNode * reverse(ListNode * head) {
        // write your code here
        ListNode *p_front = head,*p_insert = NULL;
        
        while(p_front && (p_insert = p_front->next))
        {
           p_front->next = p_insert->next;
           p_insert->next = head;
           head = p_insert;
        }
        
        return head;
    }
};

方法二:

//方法二
//和方法一基本相同 不同是 先将prev置为NULL,使第一个结点也参与逆序操作
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The new head of reversed linked list.
     */
    ListNode *reverse(ListNode *head) {
        ListNode *prev = NULL;
        while (head != NULL) {
            ListNode *temp = head->next;
            head->next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
};

    原文作者:supermuscleman
    原文地址: https://blog.csdn.net/supermuscleman/article/details/79330862
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞