Reverse Nodes in k-Group LeetCode Java

來源:互聯網
上載者:User

標籤:i++   ==   val   修改   you   public   mem   nod   next   

描述
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then le-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example, Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

分析

給定鏈表,一次反轉鏈表k的節點並返回其修改的列表。
如果節點的數目不是k的倍數,那麼最終的節點應該保持原樣。
可能不會更改節點中的值,而只能更改節點本身。

例如,給定這個鏈表:1>2>3>4>5。
對於k=2,你應該返回:2 ->1 ->4>3>5。
對於k=3,你應該返回:3 ->2 ->1>4>5。

注意越界問題,

代碼

 1 public static ListNode reverseNodeInKGrop(ListNode head, int n) { 2         if (head == null || head.next == null || n == 1) 3             return head; 4         ListNode fakehead = new ListNode(-1); 5         fakehead.next = head; 6         ListNode ptr1 = head, ptr2 = fakehead.next.next, newstart = fakehead; 7         int len = 0; 8         while (ptr1 != null) { 9             len++;10             ptr1 = ptr1.next;11         }12         ptr1 = fakehead.next;13         if(n!=len)14            n = n % len;15         int k = len / n;16         for (int j = 0; j < k; j++) {17 18             for (int i = 1; i < n; i++) {19                 ptr1.next = ptr2.next;20                 ptr2.next = newstart.next;21                 newstart.next = ptr2;22                 ptr2 = ptr1.next;23             }24             25             for (int i = 0; i < n; i++) {26                 newstart = newstart.next;27             }28 29             if (ptr2 != null && ptr2.next != null) {30                 ptr1 = newstart.next;31                 ptr2 = ptr1.next;32             }33         }34 35         return fakehead.next;36     }

 

Reverse Nodes in k-Group LeetCode Java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.