有一個單鏈表,請設計一個算法,使得每K個節點之間逆序,如果最後不夠K個節點一組,則不調整最後幾個節點。例如鏈表1->2->3->4->5->6->7->8->null,K=3這個例子。調整後爲,3->2->1->6->5->4->7->8->null。因爲K==3,所以每三個節點之間逆序,但其中的7,8不調整,因爲只有兩個節點不夠一組。
給定一個單鏈表的頭指針head,同時給定K值,返回逆序後的鏈表的頭指針。
將單向鏈表完全翻轉:
public static ListNode reverse(ListNode start){ ListNode cur= start; ListNode pre = null; ListNode next= null; while(cur!=null){ next = cur.next; cur.next= pre; //同步向後移動 pre = cur; cur = next; } return pre; }每k個元素翻轉一次
完整代碼:
public class LinkNode { public static class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } public ListNode() { // TODO Auto-generated constructor stub } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ListNode test = new ListNode(0); ListNode cur = test; for (int i = 1; i < 3; i++) { cur.next=new ListNode(i); cur = cur.next; } ListNode read = new ListNode(); read=inverse(test, 3); while (read!=null) { System.out.println(read.val); read=read.next; } } public static ListNode inverse (ListNode head,int k){ if(k<2) return head; ListNode cur=head; ListNode pre=null; ListNode start = null; ListNode next = null; int count =1 ; while (cur!=null) { next= cur.next; if (count==3) { start=pre==null?head:pre.next; //第一次便可以確定頭結點,以後頭結點保持不變 head=pre==null?cur:head; //將需要翻轉的區間使用pre和right封閉。對區間內部的進行完全鏈表翻轉 //然後將頭結點和尾結點與pre和right相連接,保持鏈表的連續性. reverse(pre, start, cur, cur.next); //翻轉後的頭結點將變成尾結點,作爲下一次的pre pre=start; //基數器清零 count=0; } cur=next; count++; } return head; } public static void reverse(ListNode left,ListNode start,ListNode end,ListNode right){ ListNode cur= start; ListNode pre = left; ListNode next= null; while(cur!=right){ next = cur.next; cur.next= pre; //同步向後移動 pre = cur; cur = next; } if (left!=null) { left.next=end; } start.next=right; } }參考博客:
http://blog.csdn.net/kerryfish/article/details/24043099