【java】61. 旋转链表---记录链表前一个结点,并设置该节点的next属性为null,踩坑的一天!!!

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
示例 2:
输入:head = [0,1,2], k = 4
输出:[2,0,1]
提示:
链表中节点的数目在范围 [0, 500] 内
-100 <= Node.val <= 100
0 <= k <= 2 * 109

代码:
public ListNode rotateRight(ListNode head, int k) {
    
    
		  ListNode p=head,pend=null,p1=null;
		  int count=0;
          if(k==0||head==null){
    
    
              return head;
          }
		  while(p!=null) {
    
    
			  count++;
			  pend=p;
			  p=p.next;
		  }
		  count=count-k%count;
		  if(count==0) {
    
    
			  return head;
		  }
		  p=head;
		  for(int i=0;p!=null;p=p.next,i++) {
    
    
			  if(i==count) {
    
    
				  p1.next=null;
				  pend.next=head;
				  return p;
			  }
			  p1=p;
		  }
    	  return head;
      }

猜你喜欢

转载自blog.csdn.net/qq_44461217/article/details/115307167