1.旋转链表
给定一个链表,旋转链表,将链表每个节点向右移动k个位置,其中k是非负数。
思路:先定义一个quick指针向前移动k步,如果k大于节点数,则从回到开始节点。然后slow指针指向开始节点同quick指针一同移动直到quick指针到链表尾部。slow指针的下一个节点即为新链表的头节点,quick指针指向之前链表的头节点。
直接按k循环会超时,先取余再循环。
ListNode* rotateRight(ListNode* head, int k) {
if(head == nullptr)
{
return head;
}
//计算链表的长度
int len = 1;
ListNode* ptr = head;
while(ptr -> next != nullptr)
{
len++;
ptr = ptr -> next;
}
ListNode* quick = head;
ListNode* slow = head;
ListNode* res = nullptr;
//计算循环次数
int times;
if(k < len)
{
times = k;
}
else if(k == len)
{
return head;
}
else
{
times = k % len;
}
for(int i = 0; i < times; i++)
{
if(quick -> next == nullptr)
{
quick = head;
}
else
{
quick = quick -> next;
}
}
while(quick -> next != nullptr)
{
quick = quick -> next;
slow = slow -> next;
}
if(slow -> next == nullptr)
{
return head;
}
res = slow -> next;
quick -> next = head;
slow -> next = nullptr;
return res;
}
2.简化路径
以unix风格给出一个文件的绝对路径,你需要简化它。或者换句话说,将其转换为规范路径。
以unix风格的文件系统中,一个点表示当前目录本身;此外,两个点表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分。
返回的规范路径必须始终以斜杠/开头,并且两个目录名之间必须只有一个斜杠/。最后一个目录名(如果存在)不能以/结尾。此外,规范路径必须是表示绝对路径的最短字符串。
思路:(心累。。。)
string simplifyPath(string path) {
int start = 0;
path += "/";
while(start < path.length())
{
if(path[start] == '/')
{
start++;
}
else
{
break;
}
}
stack<string> s;
string res;
vector<string> dir;
for(int i = start + 1; i < path.length();)
{
if(path[i] == '/')
{
dir.push_back(path.substr(start, i - start));
start = i + 1;
while(path[start] == '/' && start < path.length())
{
start++;
}
i = start + 1;
}
else
{
i++;
}
}
for(int i = 0; i < dir.size(); i++)
{
if(dir[i] == ".")
{
continue;
}
else if(dir[i] == "..")
{
if(s.empty())
{
continue;
}
else
{
s.pop();
}
}
else
{
s.push(dir[i]);
}
}
while(!s.empty())
{
res = s.top() + "/" + res;
s.pop();
}
if(res.length() == 0)
{
return "/";
}
res = "/" + res;
return res.substr(0, res.length() - 1);
}