给出一个链表,每 个节点一组进行翻转,并返回翻转后的链表。

  k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 的整数倍,那么将最后剩余节点保持原有顺序。

  示例 :

  给定这个链表:1->2->3->4->5

  当 = 2 时,应当返回: 2->1->4->3->5

  当 = 3 时,应当返回: 3->2->1->4->5

  说明 :

  • 你的算法只能使用常数的额外空间。
  • 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

 

  

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 
10 /*
11     通过递归的方式
12 */
13 class Solution {
14     public ListNode reverseKGroup(ListNode head, int k) {
15         ListNode end=head;
16         int n=0;
17         for(int i=0;i<k;i++){
18             //若此时节点总数不足k,则直接返回头结点
19             if(end==null)
20                 return head;
21             else
22                 end=end.next;
23         }
24         ListNode next=head.next;
25         ListNode tmphead=head;
26         //进行翻转
27         for(int i=1;i<k;i++){
28             ListNode tmp=next.next;
29             next.next=tmphead;
30             tmphead=next;
31             next=tmp;
32         }
33         //递归,将下一个结点传入
34         head.next=reverseKGroup(end,k);
35         return tmphead;
36     }
37 }

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!