Rotate a linked list

/*
	This implementation demonstrates how to 
	efficiently shift a singly linked list
	in place by k positions.

	Example: 
	shifting 0-> 1 -> 2 -> 3 -> 4-> null 
	by 2 positions yields: 
	3 -> 4 -> 0 -> 1 -> 2 -> null

	
	Let n be the number of nodes in the list.
	Time complexity: O(n) 
	Space complexity: O(1)
*/
public class LinkedListShifting {
	private ListNode head;

	public LinkedListShifting() {
		/*
		 * Create below linked list
		 * 0 -> 1 -> 2 -> 3 -> 4 -> null
		 */
		head = new ListNode(0, null);
		ListNode prev = head, temp;
		for (int i = 1; i <= 4; i++) {
			temp = new ListNode(i, null);
			prev.next = temp;
			prev = temp;
		}
	}

	public static void main(String[] args) {
		LinkedListShifting application = new LinkedListShifting();
		application.head = application.shiftLinkedList(2);
		System.out.println(application.head.val); // 3
	}

	public ListNode shiftLinkedList(int k) {
		if (head == null) {
			return null;
		}
		int length = 1;
		ListNode listTail = head;
		// Count the number of list nodes
		while (listTail.next != null) {
			listTail = listTail.next;
			length++;
		}
		// The offset should less than length
		int offset = Math.abs(k) % length;
		if (offset == 0)
			return head; // no shifting is needed
		int newTailPosition = k > 0 ? length - offset : offset;
		ListNode newTail = head;
		for (int i = 1; i < newTailPosition; i++) {
			newTail = newTail.next;
		}
		ListNode newHead = newTail.next;
		newTail.next = null;
		listTail.next = head;
		return newHead;
	}

	// Class representing a linked list node
	// with pointers to value and next node
	private class ListNode {
		int val;
		ListNode next;

		ListNode(int val, ListNode next) {
			this.val = val;
			this.next = next;
		}
	}
}

rotate linked list

def rotate(self, k):
  if self.head and self.head.next:
    p = self.head 
    q = self.head 
    prev = None
    count = 0
    
    while p and count < k:
        prev = p
        p = p.next 
        q = q.next 
        count += 1
    p = prev
    while q:
        prev = q 
        q = q.next 
    q = prev 

    q.next = self.head 
    self.head = p.next 
    p.next = None

Python相关代码片段

pathlib python

pandas excelwriter

python practise

key,value en python

linear regression in tensorflow

spark dataframe get column

drop one table sqlalchemy

python code to remove last character from string

fastapi get body on http middleware

custom neural network in keras

python selenium execute_script

db model for blog

yolov5 opencv

Get first 100 lines of file - python

python playground

print number pattern using for loop in python

ollama python

no module named 'wget'

No module named 'langchain'

failed to build wxpython

python vs c#

rabbitmq python example

change the django url prefix name

np.linspace is not defined python

LLM beguiner guide python

python parquet file to csv

python best practices

yolov5 without net

save variable as pkl python

python [-9:]

eigenface python

'DataFrame' object has no attribute 'dtype'

unable to enable maximize window tkinter

rabbit and fox numpy python

lstm in keras

neural network in keras

resnet50 in keras

autoencoder in keras

cnn in keras

tensor in keras

pyTelegramBotAPI edit photo

print api python

how to get values but not index from pandas series

how to get mode of a column from pandas

bayesian neural network pymcmc

lda python

back propagation python

logical syntax is not none python

register model django

Descending Selection sort

Selection sort with while loops

Selection sort with for loops

Doubling Algorithm for cluster analysis in python

Tkinter widgets

nameerror: name 'callable' is not defined

NameError: name 'Union' is not defined

Make a widget customtkinter python

nn module pytorch

import tf python

Spark SEssion object

Implement Bubble sort with while loops

Unoptimized bubble sort algorithm

Optimized bubble sort algorithm

how to get today's date in python

st_aggrid install

python venv pip blocked by admin windows

numpy matrix from lists of different leght

python postgres auto commit

dotenv install python

np mean axis

LinkExtractor Object

admin django documentation

Python native Convolution implementation

is django monolithic

what is function call with an llm

np array to series

dht22 micropython pico

disable slash command discord.py

python docker compose not printing

tabnet probabilities