leecode第六十一题(旋转链表)

时间:2023-03-09 21:44:22
leecode第六十一题(旋转链表)

leecode第六十一题(旋转链表)

/**
* 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==NULL)//特殊情况-空
return NULL;
if(head->next==NULL)//特殊情况-只有一个节点
return head; ListNode* node=head;
int len=;
while(node->next!=NULL)//获得长度
{
node=node->next;
len++;
} node=head;
int n=len-k%len;
for(int i=;i<(n-);i++)//计算并得到新的头节点之前的那个节点
node=node->next; if(node->next==NULL)//若这个节点是原尾节点,直接返回原数组
return head;
ListNode* new_head=node->next;//若不是,干三件事,第一得到新的头结点
node->next=NULL;//第二把新头结点前的节点的next赋NULL
node=new_head;
while(node->next!=NULL)//第三把原尾节点的next由NULL改为原头结点
node=node->next;
node->next=head; return new_head;
}
};

分析:

这个算法时间复杂度,因为只是遍历两遍链表,理论上是O(n),为了得到链表长度多遍历一遍,想了半天也没有其他的路子,后来想想相比一点点挪应该是快的吧。

写的时候有两个关键地方第一时间都没想到,第一是新节点的计算,由于举得案例不全,也巧合,导致我一开始写的不对。第二是没注意到新的节点就是头结点的情况,因为我这个算法最后面还有while循环,所以没有考虑到这个情况的时候,这个是死循环。

今天真的不能再做了,太累了。