链表反转:
转自这里
public Node reverse(Node head){
if(head==null || head.next==null) return head;
Node temp=head.next;
Node newHead=reverse(head.next);
temp.next=head;
head.next=null;
return newHead;
}
public Node reverse(Node head) {
Node pre = null, next = null;
while (head != null) {
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
k个一组链表反转(leetcode 25):
转自leetcode 25题
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dum = new ListNode(0);
dum.next=head;
ListNode pre=dum,end=dum;
while(end.next!=null){
for(int i=0;i<k&&end!=null;i++) end=end.next;
if(end==null) break;
ListNode start=pre.next;
ListNode next=end.next;
end.next=null;
pre.next=reverse(start);
start.next=next;
end=start;
pre=start;
}
return dum.next;
}
public ListNode reverse(ListNode head){
if(head==null || head.next==null) return head;
ListNode temp = head.next;
ListNode newHead = reverse(head.next);
temp.next=head;
head.next=null;
return newHead;
}
}