LeetCode--025--k个一组翻转链表(java and python)

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

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

示例 :

给定这个链表: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 class Solution {
10     public ListNode reverseKGroup(ListNode head, int k) {
11         if(head == null || head.next == null) return head;
12         int count = 0;
13         ListNode cur = head;
14         while(cur != null && count != k){
15             cur = cur.next;
16             count++;
17         }
18         if(count == k){
19             cur = reverseKGroup(cur,k);//cur 是上一次反转后的头结点
20             while(count-- >0){//基本的反转语句要掌握
21                 ListNode temp = head.next;
22                 head.next = cur;
23                 cur = head;
24                 head = temp;
25             }
26             head = cur;
27         }
28         return head;
29     }
30 }

2019-04-20 17:50:52

python版本

start到end为当前要翻转的部分

 1 class Solution:
 2     def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
 3         dummy=pre=start=end = ListNode(-1)
 4         dummy.next=head
 5         while end.next!=None:
 6             for i in range(k):
 7                 if end!=None:
 8                     end=end.next
 9                 else:
10                     break
11             if end==None:
12                 break
13             start = pre.next
14             next=end.next
15             end.next=None
16             pre.next = self.reverse(start)
17             start.next=next
18             pre=start
19             end=pre
20         return dummy.next
21     def reverse(self,cur):
22         pre = ListNode(-1)
23         pre.next=None
24         while cur!=None:
25             q = cur.next
26             cur.next=pre
27             pre=cur
28             cur = q
29         return pre
原文地址:https://www.cnblogs.com/NPC-assange/p/10741845.html