Reverse Nodes in k-Group leetcode

来源:互联网 发布:java图书管理系统报告 编辑:程序博客网 时间:2024/05/01 09:42

Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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值有关,如上所示,  对于  1->2->3->4->5   当k=2时   2->1->4->3->5

             当k=3时   3->2->1->4->5后面 4 5没变是因为做完一次 3 2 1 剩下的  4 5 已经比k小了,所以保持原来的顺序

思路:

1、先 求出链表总的元素个数temp

2、创建一个头结点result,用来指向result->next=head,并保存头节点reverhead=result;

3、 用temp和k的值比较  while(k<=temp) 当k小于等于temp时就进行逆置操作

4、设置部分逆置长度   ,令 t=k ,  while(t>0) 进行部分逆置 

5、temp=temp-k   最后返回  reverhead->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) {                ListNode *p=head,*q,*reverhead;        int temp=0;        int t;                while(p)        {            ++temp;            p=p->next;        }        if(temp==0||1==k||k>temp)            return head;        ListNode *result=new ListNode(0);//创建头结点 并用reverhead保存头结点        result->next=head;        reverhead=result;        p=result->next;   //用p来指向下一个节点,进行操作的第一个有效节点                       while(k<=temp) //外层循环用k和temp        {            t=k;     //里层循环每次操作t个                      ListNode *remark=p;  //用remark保存每次进行部分逆置的第一个节点,该节点将指向部分逆置的下一个节点,如上k=2时,1指向3            while(t>0)    //将p开始的t个节点进行逆置            {                q=p;                p=p->next;                q->next=result->next;                result->next=q;                t--;            }            remark->next=p; //将每部分连接起来            result=remark;  //改变result,指向部分逆置的最后一个节点                        temp=temp-k; //做了部分逆置后,改变temp        }                return reverhead->next;     }};



0 0
原创粉丝点击