標籤:
Reverse Nodes in k-Group
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
分析
1.鏈表反轉:
給一個單向鏈表,把它從頭到尾反轉過來。比如: a -> b -> c ->d 反過來就是 d -> c -> b -> a 。
這裡講解兩種方法:
第一種方法就是把每個Node按照順序存入到一個stack裡面,這樣,最後面一個就在最上面了。然後,把每一個再取出來,這樣順序就換過來了。
public static Node reverse(Node head) { Stack<Node> stack = new Stack<Node>(); // put all the nodes into the stack while (head != null) { stack.add(head); head = head.next(); } //reverse the linked list Node current = stack.pop(); head = current; while (stack.empty() != true) { Node next = stack.pop(); //set the pointer to null, so the last node will not point to the first node. next.setNext(null); current.setNext(next); current = next; } return head; }
2.用兩個指標
第二種方法就是利用兩個指標,分別指向前一個節點和當前節點,每次做完當前節點和下一個節點的反轉後,把兩個節點往下移,直到到達最後節點。
public static Node reverse(Node head) { Node previous = null; while (head != null) { Node nextNode = head.next(); head.setNext(previous); previous = head; head = nextNode; } return previous; }
所以本題用兩個指標的方式:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode reverselist(ListNode pre,ListNode next){ ListNode last=pre.next; ListNode cur=last.next; while(cur!=next){ last.next=cur.next; cur.next=pre.next; pre.next=cur; cur=last.next; } return last; } public ListNode reverseKGroup(ListNode head, int k) { if(head==null||head.next==null){ return head; } ListNode newhead=new ListNode(0); newhead.next=head; ListNode pre=newhead; ListNode cur=head; int count=0; while(cur!=null){ count++; ListNode next=cur.next; if(count==k){ pre=reverselist(pre,next); count=0; } cur=next; } return newhead.next; }}
Linked List專題二(cc charpter2)