继续刷leetcode,第61题,求一个旋转链表;
分析:
首先找到尾指针,然后将尾指针与头连接,然后找到倒数第k-1个节点,然后将该节点与后一个断开,然后头设置为该节点的下一个,返回;
问题:
1、注意链表为空;
2、k为0等情况;
附上c++代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head)
return NULL;
int n=1;
ListNode * p=head;
while(p->next!=NULL)
{
p=p->next;
n++;
}
k=n-k%n;
p->next=head;
ListNode * q=p;
while(k--)
q=q->next;
ListNode * newHead=q->next;
q->next=NULL;
return newHead;
}
};
附上python代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head:
return None
n=1
cur=head
while cur.next:
n+=1
cur=cur.next
cur.next=head
n=n-k%n
while n:
cur=cur.next
n-=1
newHead=cur.next
cur.next=None
return newHead