码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode LinkList专题

时间:2015-05-06 17:54:05      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:linklist   leetcode   

此次blog会将leetcode上的linklist专题内容放在这里,后续慢慢添加

一:leetcode 206 Reverse Linked List  二:leetcode 92 Reverse Linked List II

一:leetcode 206 Reverse Linked List

题目:

Reverse a singly linked list.

代码:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL) return NULL;
        ListNode *p = head;
        ListNode *pNext = p->next;
        p->next = NULL;       // 头结点需要指向NULL 否则time limit
        while(pNext != NULL){
            ListNode *q = pNext->next;
            pNext->next = p;
            p = pNext;   // 迭代
            pNext = q;
        }
        return p;
        
    }
};
二:leetcode 92 Reverse Linked List II

题目:

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

分析:此题比一稍微复杂一点,但是也是很容易求解的

代码:

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if(m == n) return head;
        ListNode *pre = head;
        ListNode *p = head;
        for(int i = 1; i < m; i++){    // 找到第m个元素和其前一个元素
            pre = p;
            p = p->next;
        }
        ListNode *curr = p;
        ListNode *pNext = p->next;   // 对中间需要进行reverse的元素进行反转 利用reverse linked list中的思想
        for(int i = m; i < n; i++){
            ListNode *q = pNext->next;
            pNext->next = p;
            p = pNext;
            pNext = q;
        }
        curr->next = pNext;
        if(pre != curr)pre->next = p;      // 不相等表明是m!=1  那么 则pre->next = p,,相等表明m==1,那么head ==p
        else head = p;
        return head;
        
    }
};



leetcode LinkList专题

标签:linklist   leetcode   

原文地址:http://blog.csdn.net/lu597203933/article/details/45537075

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!