leetcode 旋转链表实现
题目描述:给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
python代码实现:
class Solution(object):
# 此方法实现链表向右移动一位,则只需要调用k次此方法
def rotate(self,head):
if not head or not head.next:
return head
p = head
q = p.next
while q.next:
p=p.next
q=q.next
#q 最后一个节点
p.next=None
q.next = head
return q
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head:
return head
length=0
cur = head
while cur:
length+=1
cur = cur.next
# 保证一次到位,不做重复工作
k%=length
j=0
while j<k:
head=self.rotate(head)
j+=1
return head
运行截图:
C语言代码实现:
struct ListNode* rotate(struct ListNode* head){
if(head==NULL||head->next==NULL)
return head;
struct ListNode* p=head;
struct ListNode* q=head->next;
while(q->next!=NULL){
p=p->next;
q=q->next;
}
//q最后一个节点
q->next=head;
p->next=NULL;
return q;
}
struct ListNode* rotateRight(struct ListNode* head, int k){
struct ListNode* cur =head;
int len=0;
while(cur!=NULL){
len++;
cur=cur->next;
}
if(len==0||len==1){
return head;
}
k%=len;
int i=0;
while(i<k){
head=rotate(head);
i++;
}
return head;
}
运行截图: