反转链表
2015-10-22 16:23
573 查看
public class Solution {
public ListNode reverse(ListNode head, ListNode end){
if(head==null || head.next==null || head==end || head.next==end) return head;
ListNode sec = head.next;
ListNode rem = reverse(sec,end);//递归,直到返回head
sec.next =head; head.next=null;//实现反转
return rem;
}
public ListNode reverseKGroup(ListNode head, int k) {//分组反转
ListNode curr = head; int count = 0;
while (curr != null && count != k) {
curr = curr.next;count++;
}
if (count == k) {
ListNode temp = reverseKGroup(curr, k);
ListNode t = reverse(head,curr);
head.next = temp;
return t;
}
return head;
}
}
public ListNode reverse(ListNode head, ListNode end){
if(head==null || head.next==null || head==end || head.next==end) return head;
ListNode sec = head.next;
ListNode rem = reverse(sec,end);//递归,直到返回head
sec.next =head; head.next=null;//实现反转
return rem;
}
public ListNode reverseKGroup(ListNode head, int k) {//分组反转
ListNode curr = head; int count = 0;
while (curr != null && count != k) {
curr = curr.next;count++;
}
if (count == k) {
ListNode temp = reverseKGroup(curr, k);
ListNode t = reverse(head,curr);
head.next = temp;
return t;
}
return head;
}
}
相关文章推荐
- LeetCode_Regular Expression Matching
- Leetcode_Add Two Numbers
- Merge k Sorted Lists -- LeetCode
- Reverse Nodes in k-Group
- LeetCode 2. Add Two Numbers
- Add Two Numbers(OC版)
- 24. Swap Nodes in Pairs
- [LeetCode]19. Remove Nth Node From End of List
- java链表ListNode
- java ListNode链表求和
- 92. Reverse Linked List II
- LeetCode-203. Remove Linked List Elements
- leetcode之Linked List Random Node
- LeetCode – Remove Nth Node From End of List (Java)
- LeetCode 2. Add Two Numbers(单链表求和)
- leetcode【第四周】 交换节点对
- leetcode【第十四周】从排序列表中移除重复元素Ⅱ
- leetcode-83 Remove Duplicates from Sorted List
- 双链表的创建、排序、删除、查找、合并
- 【LeetCode】C# 2、Add Two Numbers