博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode-25 Reverse Nodes in k-Group
阅读量:4135 次
发布时间:2019-05-25

本文共 1677 字,大约阅读时间需要 5 分钟。

题目

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

解答

这里写图片描述

代码:

/** * 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) {        if(head==NULL||k==1) return head;        ListNode *preheader=new ListNode(-1);//new a listnode,whose next points to head        preheader->next=head;        ListNode *cur=head,*pre=preheader,*nex;        //calculate the length of the List        int num=0;        while(cur)        {            num++;            cur=cur->next;        }        while(num>=k)        {            cur=pre->next;            nex=cur->next;//nex is the next of cur pointer            for(int i=1;i
next=nex->next; nex->next=pre->next; pre->next=nex; nex=cur->next;//after one adjustment, nex points to cur->next }//if this has been done,it indicates the k nodes have been palced in the reverse position.Then ,turn to the next k nodes. pre=cur; num=num-k;//num should subtract k } return preheader->next; }};

画一遍确实帮助理解!

你可能感兴趣的文章
移植Linux2.6.39到杨创utu2440
查看>>
关于ARM的22个常用概念--的确经典
查看>>
kernel panic No init found的一种解决办法
查看>>
I2C从机挂死分析和解决方法
查看>>
USB OTG功能是什么意思?
查看>>
手机中电容屏和电阻屏有什么区别?
查看>>
Linux终端设备驱动 ----UART的驱动
查看>>
uCGUI使用
查看>>
Linux下SPI驱动的移植和应用程序的测试
查看>>
mini210使用tftp功能
查看>>
mini210的uboot编译使用
查看>>
Sizeof与Strlen的区别与联系
查看>>
Linux Kernel and Android 休眠与唤醒(request_suspend_state)
查看>>
mini210的串口驱动的应用程序
查看>>
Linux tar打包命令
查看>>
编译友善之背的mini210的android文件系统
查看>>
ucosII的CPU使用率查看即OSStatInit()函数的使用方法
查看>>
STM32上使用UCOSII--软件定时器和任务延时
查看>>
IAR上部分UCOS软定时器无法启动的问题
查看>>
ucosII的事件标志组的使用心得
查看>>