Reverse every k nodes of a linked list

前端 未结 7 1007
夕颜
夕颜 2020-12-15 01:42

I am preparing for a technical interview and I am stuck at writing this program to reverse every k nodes of a linked list.

For example

1->2->3         


        
7条回答
  •  感情败类
    2020-12-15 02:00

    Yeah, I have never been a fan of recursion, so here is my shot at it using iteration:

      public Node reverse(Node head, int k) {
           Node st = head;
           if(head == null) {
             return null;
           }
    
           Node newHead = reverseList(st, k);
           st = st.next;  
    
           while(st != null) {
             reverseList(st, k);
             st = st.next;
           } 
    
           return newHead
    
      }
    
    
     private Node reverseList(Node head, int k) {
    
          Node prev = null;
          Node curr = head;
          Node next = head.next;
    
          while(next != null && k != 1){
           curr.next = prev;
           prev = curr;
           curr = next;
           next = next.next;
           --k;
          }
          curr.next = prev;
    
          // head is the new tail now.
          head.next = next;
    
          // tail is the new head now.
          return curr;
     }
    

提交回复
热议问题