lintcode 翻转链表

三十五题为翻转一个单链表,三十六题为翻转链表中第m个节点到第n个节点的部分
样例
给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null。
先来说三十五,翻转一个单链表。
每次点到一个节点作为链表的开始即可:

/**
 * Definition of ListNode
 * 
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 * 
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The new head of reversed linked list.
     */
    ListNode *reverse(ListNode *head) {
        // write your code here
        ListNode* pre = NULL;
        while (head) {
            ListNode* next = head -> next;
            head -> next = pre;
            pre = head;
            head = next;
        } 
        return pre;
    }
};

还有个更简单的递归方法:

/**
 * Definition of ListNode
 * 
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 * 
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The new head of reversed linked list.
     */
    ListNode *reverse(ListNode *head) {
        // write your code here
        if (!head || !(head -> next)) return head;
        ListNode* node = reverse(head -> next);
        head -> next -> next = head;
        head -> next = NULL;
        return node; 
    }
};

对于给定区间的情况。首先创建一个ptr指向头结点,并使用他来定位到第m个节点之前的节点,将cur设置为pre之后的节点,每次将cur之后的节点(move)移动到pre之后的节点,重复n-m次:

/**
 * 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: The head of linked list.
     * @param m: The start position need to reverse.
     * @param n: The end position need to reverse.
     * @return: The new head of partial reversed linked list.
     */
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        // write your code here
        ListNode *ptr = new ListNode(0);
        ptr->next = head;
        ListNode *pre = ptr;
        for (int i = 1;i < m;i++) {
            pre = pre->next;
        }
        ListNode *cur = pre->next;
        for (int i = 0;i < n - m;i++) {
            ListNode *move = cur->next;
            cur->next = move->next;
            move->next = pre->next;
            pre->next = move;
        }
        return ptr->next;
    }
};

你可能感兴趣的:(lintcode 翻转链表)