Reverse Nodes in k-Group

原创 2015年07月08日 19:20:12

这道题目,我的解法思想与Swap Nodes in Pairs那道题基本上是一样的,只不过在翻转group内节点的时候,我使用了数组栈。我的代码如下:

    ListNode* reverseKGroup(ListNode* head, int k) {
        int cnt = 0; // 计数
        ListNode *sstack[k], *cursor; // 数组栈
        ListNode dummy(0), *pre = &dummy, *p = head; // p为待翻转group的第一个节点
        pre->next = head; // pre为p之前的节点
        while (p) {
            cnt = k;
            cursor = p;
            
            for (int i=0; i<k; i++) {
                if (cursor == NULL) {
                    return dummy.next;
                }
                sstack[i] = cursor; // group内节点入栈
                cursor = cursor->next;
            }
            
            for (int i=k-1; i>=1; i--) { // 翻转group内各节点
                sstack[i]->next = sstack[i-1];
            }
            
            pre->next = sstack[k-1]; // 一些连接操作
            p->next = cursor;
            pre = p;
            p = p->next;
         
        }
        return dummy.next;
    }




相关文章推荐

25. Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. I...

leetcode025:Reverse Nodes in k-Group

问题描述 Given a linked list, reverse the nodes of a linked list k at a time and return its modified l...

leetcode之Partition List,Reverse Nodes in k-Group

Partition List Given a linked list and a value x, partition it such that all nodes less than x com...

leetcode25---Reverse Nodes in k-Group

问题描述: Given a linked list, reverse the nodes of a linked list k at a time and return its modified l...
  • will130
  • will130
  • 2015年12月20日 23:59
  • 277

LeetCode (25) Reverse Nodes in k-Group (链表)

题目描述Given a linked list, reverse the nodes of a linked list k at a time and return its modified list...

LeetCode 25. Reverse Nodes in k-Group

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

[Leetcode] Reverse Nodes in k-Group (Java)

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. I...

Reverse Nodes in k-Group

题目 Given a linked list, reverse the nodes of a linked list k at a time and return its modified list...
  • Boyhou
  • Boyhou
  • 2013年07月29日 00:27
  • 631

算法设计与分析(18)-- Reverse Nodes in k-Group(难度:Hard)

Reverse Nodes in k-Group

[LeetCode]25.Reverse Nodes in k-Group

【题目】 Given a linked list, reverse the nodes of a linked list k at a time and return its modified l...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Reverse Nodes in k-Group
举报原因:
原因补充:

(最多只允许输入30个字)