标签:
Use 3 pointers each of them points to the address of Head, The node before Tail and Tail node; When rotating the list step by step, tail.next = head; tail_prev.next = null. New head = tail and new Tail = tail_prev;
Code: (Recursion way)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null || head.next == null) return head; ListNode cur = head; int len = 0; while(cur != null && cur.next != null){ cur = cur.next; len++; } if(cur != null) len++; k = k % len; if(k == 0) return head; ListNode tail = cur; ListNode newHead = rotateOneStep(head, tail, k); return newHead; } public ListNode rotateOneStep(ListNode head, ListNode tail, int num){ ListNode tail_prev = head; while(tail_prev != null && tail_prev.next.next != null) tail_prev = tail_prev.next; tail.next = head; tail_prev.next = null; if(num == 1) return tail; head = tail; tail = tail_prev; return rotateOneStep(head, tail, num-1); } }
Code(Iteration way):
public class Solution { //ListNode newHead, newTail; public ListNode rotateRight(ListNode head, int k) { if(head == null || head.next == null) return head; ListNode cur = head; int len = 0; while(cur != null && cur.next != null){ cur = cur.next; len++; } if(cur != null) len++; k = k % len; ListNode tail = cur; for(int i = 0; i < k; i++){ ListNode tail_prev = head; while(tail_prev != null && tail_prev.next.next != null) tail_prev = tail_prev.next; tail.next = head; tail_prev.next = null; head = tail; tail = tail_prev; } return head; }
Code. Use List to store each node:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null || head.next == null) return head; List<ListNode> findPrev = new ArrayList<>(); ListNode cur = head; int len = 0; while(cur != null && cur.next != null){ findPrev.add(cur); cur = cur.next; len++; } if(cur != null) { findPrev.add(cur); len++; } k = k % len; ListNode tail = cur; for(int i = 0; i < k; i++){ ListNode tail_prev = findPrev.get(len-2); tail.next = head; tail_prev.next = null; head = tail; tail = tail_prev; findPrev.add(0, findPrev.remove(len-1)); } return head; } }
Jan 19 - Rotate List; Linked List; Two Pointers; Iteration & Recursion;
标签:
原文地址:http://www.cnblogs.com/5683yue/p/5143947.html