Leetcode 25.Reverse Nodes in k-Group

原题地址:https://leetcode.com/problems/reverse-nodes-in-k-group/description/

题目描述

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

就是说以k个节点为单位,把链表里每k个节点的值的顺序反转。剩下的不足k个的节点不用处理。

解题思路

一个指针current用于遍历链表,一个指针last_pos用于保存上一次更新结束以后更新到的范围,一个vector用来存放节点值,一个整数count用来计数。
current遍历链表,每遍历满k个就从last_pos指向的节点开始,更新k个节点,值从vector里取。一次更新完之后清空vectorcount置0,反复操作直到链表的尽头。

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        vector<int> vec;
        ListNode * last_pos =head;
        ListNode * current = head;
        int count = 0;
        while(current!=NULL ){
            vec.push_back(current->val);
            count++;
            current=current->next;
            if(count==k){
                for(int i =0;i<k;i++){
                    last_pos->val = vec[vec.size()-1-i];
                    last_pos=last_pos->next;
                }
                vec.clear();
                count=0;
            }
        }
        return head;
    }
};

坑点:

不存在的。

TIM截图20170917003235.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 哎,人啊,相处久了多多少少会有些摩擦矛盾,无论如何也避免不了。闹心,各自关上门寻求一片宁静!
    Lynn欧尼阅读 486评论 0 0
  • 大理贴诗记04:银苍路 文/乌青 银苍路的最上端行人很稀少,这个点是我们很早以前就看过的,离我们住处比较远,今天下...
    这里有诗阅读 445评论 1 8