链表中的节点每k个一组翻转

链表中的节点每k个一组翻转

http://www.nowcoder.com/questionTerminal/b49c3dc907814e9bbfa8437c251b028e

  1. 初始化头节点与尾节点

  2. 使用头插法将后续 K-1 个节点插入头节点与尾节点之间,使前 K 个节点倒转,然后更新头节点与尾节点。

  3. 循环上述步骤,直至尾部节点的 Next 指向 nil 或 插入的节点数小于 k-1,返回链表头节点。

  4. 1 对于插入节点小于 k-1,此时需要将逆转的节点进行还原,然后返回链表头节点。

    package main
    import . "nc_tools"
    func reverseKGroup( head *ListNode ,  k int ) *ListNode {
      // write code here
      if head == nil{
          return nil
      }
      root := &ListNode{Val: 0,Next: nil}
      root.Next = head
      tmproot := root 
      cur := head
      next := cur.Next    
      for{
          i:=1
          for ;i<k && next != nil;i++{
    
              cur.Next = next.Next     
              tmproot.Next,next.Next = next,tmproot.Next 
              next = cur.Next
    
          }
    
          if i==k{
              if cur.Next != nil{
                  tmproot = cur
                  cur = tmproot.Next
                  next = cur.Next   
              }else{
                  break
              }
    
          }else{
              for j:=1;j<i;j++{
                  t := tmproot.Next
                  tmproot.Next = tmproot.Next.Next
    
                  //t2 := cur.Next
                  cur.Next,t.Next = t,cur.Next
                  //t.Next = t2
    
              }
              break
          }
      }
      return root.Next    
    }
全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务