[Java] 61. Rotate the linked list --- record the previous node of the linked list, and set the next attribute of the node to null, one day! ! !

Give you the head node of a linked list, rotate the linked list, and move each node of the linked list k positions to the right.

Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Example 2:
Input: head = [0,1,2], k = 4
Output: [2,0,1]
Tip:
The number of nodes in the linked list is within the range [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;
      }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/115307167