[LeetCode]25.Reverse Nodes in k-Group

【题目】

Given a linked list, reverse the nodes of a linked listkat a time and return its modified list.

If the number of nodes is not a multiple ofkthen 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

Fork= 2, you should return:2->1->4->3->5

Fork= 3, you should return:3->2->1->4->5

【题意】

给定一个链表,一次反转链表前k个节点,并返回它的修改链表。

如果节点的数量是不k的倍数则最终留出节点应该保持原样,每K个一反转,不到k个不用反转。

【分析】

【代码】

/*********************************
*   日期:2014-01-31
*   作者:SJF0115
*   题号: Reverse Nodes in k-Group
*   来源:http://oj.leetcode.com/problems/reverse-nodes-in-k-group/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if (head == NULL || k < 2){
            return head;
        }

        ListNode *dummy = (ListNode*)malloc(sizeof(ListNode));
        dummy->next = head;

        ListNode *pre = dummy,*cur = NULL,*tail = NULL;
        //统计节点个数
        int count = 0;
        while(pre->next != NULL){
            pre = pre->next;
            count++;
        }
        //反转次数
        int rCount = count / k;
        int index = 0;
        //反转元素的前一个
        pre = dummy;
        //反转元素第一个即翻转后的尾元素
        tail = dummy->next;
        //共进行rCount次反转
        while(index < rCount){
            int i = k - 1;
            //反转
            while(i > 0){
                //删除cur元素
                cur = tail->next;
                tail->next = cur->next;
                //插入cur元素
                cur->next = pre->next;
                pre->next = cur;
                i--;
            }
            pre = tail;
            tail = pre->next;
            index++;
        }
        return dummy->next;
    }
};
int main() {
    Solution solution;
    int A[] = {1,2,3,4,5};
    ListNode *head = (ListNode*)malloc(sizeof(ListNode));
    head->next = NULL;
    ListNode *node;
    ListNode *pre = head;
    for(int i = 0;i < 5;i++){
        node = (ListNode*)malloc(sizeof(ListNode));
        node->val = A[i];
        node->next = NULL;
        pre->next = node;
        pre = node;
    }
    head = solution.reverseKGroup(head->next,5);
    while(head != NULL){
        printf("%d ",head->val);
        head = head->next;
    }
    return 0;
}


【代码】


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值