题目:
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 left-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个的时候 将其反转
思路:写一个reverse链表的方法,每当符合条件的时候调用方法即可。
代码:(自己第一次写的比较繁琐,下面有精简版)
public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if(head == null) return null; ListNode cur = head; //记录要反转的头 ListNode dep = head; //保存原始head ListNode curPre = new ListNode(0); // cur的前一个指针 其next为反转后的头 ListNode req = null; // 如果有反转的话 记录第一次的头 即最终要返回的 int count = k; // 记录next次数 while(head != null){ head = head.next; count--; if(count == 0){ //有k个非空 符合要求 ListNode temp = reverse(cur, k); if(req == null) //第一次反转 记录其头 req = temp; curPre.next = temp; cur.next = head; count = k; //计数重置 curPre = cur; //保存前一个指针 cur = head; continue; } } return req == null ? dep : req; } public ListNode reverse(ListNode head, int k){ ListNode dunmy = null; while(k > 0){ ListNode temp = head.next; head.next = dunmy; dunmy = head; head = temp; k--; } return dunmy; } }
精简之后代码(为了简化判断部分,在reverser中 传入了前一个节点)
private static ListNode reverse(ListNode pre, ListNode next){ ListNode last = pre.next;//where first will be doomed "last" ListNode cur = last.next; while(cur != next){ last.next = cur.next; cur.next = pre.next; pre.next = cur; cur = last.next; } return last; } public static ListNode reverseKGroup(ListNode head, int k) { if(head == null || k == 1) return head; ListNode dummy = new ListNode(0); dummy.next = head; int count = 0; ListNode pre = dummy; ListNode cur = head; while(cur != null){ count ++; ListNode next = cur.next; if(count == k){ pre = reverse(pre, next); count = 0; } cur = next; } return dummy.next; }
参考链接:http://www.cnblogs.com/springfor/p/3864530.html