1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| class ListNode{ private int val; private ListNode next; public ListNode(){} public ListNode(int val){ this.val = val; } public ListNode(int val,ListNode node){ this.val= val; this.next = node; } }
class Solution{ public ListNode getKreverseNode(ListNode node,int k){ ListNode dump = new ListNode(0); dump.next = node; ListNode pre = dump; ListNode end = dump; 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; ListNode reverseNode = reverse(start); pre.next= reverseNode; start.next= next; pre = start; end = pre; } return dump.next; } public ListNode reverse(ListNode node){ ListNode pre =null; ListNode cur = node; while(cur != null){ ListNode next = cur.next; cur.next= pre; pre = cur; cur = next; } return pre; } }
|