Leetcode 25. Reverse Nodes in k-Group 非递归解法

本文介绍了一种不使用递归的链表K个一组翻转算法,通过使用额外的begin和tail指针,实现了链表的局部翻转,同时保持了常数级别的额外内存消耗,满足题目要求。

题目:

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.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list's nodes, only nodes itself may be changed
  •  

给定一个链表,以及一个整数k,我们将链表每隔k个翻转一下,如题中举例所示

 

解法:

 

看到网上很多使用递归来做,这里我没有使用。主要遵循的逻辑如下:

对于每一段要反转的链表

我们需要两个指针 begin(begin是这段要反转的链表的前一个节点,这也是为什么要在header前新建的一个节点的原因) 和 tail

例如要反转 

2 ->3-> 4

初始指针位置如下:

0   ->     2    ->   3   ->   4

 |            |

begin    tail

这是我们操作3插入到2前面 

0   ->     3    ->   2   ->   4

 |                        |

begin               tail

之后我们操作4插入到3前面

0   ->    ->   4   ->   3    ->   2   

 |                                         |

begin                                 tail

 

反转完成后 

begin=tail 

tail=begin->next

开始下一段的操作

 

代码: 

 

/**
 * 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) {
        int n = 0; //length of list
        for (ListNode *i = head; i != NULL; n++, i = i->next); //count length
        ListNode *first=new ListNode(0); //add the header
        first->next=head;
        ListNode *pre=first;
        ListNode *last=head;
        for(int j=0;j<=n-k;j+=k){
            for(int i=0;i<k-1;i++){
                ListNode *next=last->next;
                last->next=next->next;
                next->next=pre->next;
                pre->next=next;
            }
            pre=last;
            last=last->next;
        }
        return first->next;
    }
};

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值