Leetcode刷题-Day4-链表
leetcode-24.两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
图示;
struct ListNode* swapPairs(struct ListNode* head){
if(head==NULL || head->next==NULL)
return head;
struct ListNode *Current = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *Past = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *Newhead = (struct ListNode*)malloc(sizeof(struct ListNode));
Current=head;
int num=1;
while(Current->next!=NULL){
num++; //统计单双数
Past=Current;
Current=Current->next;
if(num%2==0){
int n=Past->val;
Past->val=Current->val;
Current->val=n;
}
if(num==2)
Newhead=Past;
}
return Newhead;
}
思路:while(->next)遍历链表,新建2个指针Past,Current保存相邻两个节点的数据,全局变量num用于记录当前节点的单双数,以及num==2时,刷新头结点(可以不用新建Newhead)。
注意点:判断指针是否为空、只有一个节点时的状况。
leetcode-面试题 02.07. 链表相交
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
图示两个链表在节点 c1 开始相交:
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
图示:
暴力解法,边界问题都是提交报错coding的。
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode* CurrentA = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* CurrentB = (struct ListNode*)malloc(sizeof(struct ListNode));
if(headA==NULL||headB==NULL)
return NULL;
CurrentA=headA;
CurrentB=headB;
if(CurrentA->next==NULL||CurrentB->next==NULL){
while(CurrentA->next!=NULL){
CurrentA=CurrentA->next;
}
while(CurrentB->next!=NULL){
CurrentB=CurrentB->next;
}
if(CurrentA==CurrentB)
return CurrentA;
else
return NULL;
}
while(CurrentA!=NULL){
CurrentB=headB;
while(CurrentB!=NULL){
if(CurrentB==CurrentA){
return CurrentB;
}
if(CurrentB->next==NULL)
break;
CurrentB=CurrentB->next;
}
CurrentA=CurrentA->next;
}
return NULL;
}
leetcode-面试题 142. 环形链表
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos
来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos
不作为参数进行传递,仅仅是为了标识链表的实际情况。不允许修改 链表。
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/linked-list-cycle-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
https://leetcode.cn/problems/linked-list-cycle-ii/solution/huan-xing-lian-biao-ii-by-leetcode-solution/
题解的哈希算法还没了解,先用快慢指针,看看自己对双指针掌握的怎么样。
可知,c==a,所以Slow继续往前走的路程跟头节点往前走到循环起始点的路程相等。
struct ListNode *detectCycle(struct ListNode *head) {
if(head==NULL || head->next==NULL)
return NULL;
struct ListNode* Fast=head;
struct ListNode* Slow=head;
int num=0;
int n1,n2;
while(Fast->next!=NULL){
if(Fast->next->next==NULL){
return NULL;
}
Fast=Fast->next->next;
Slow=Slow->next;
num++;
if(Fast==Slow){
break;
}
}
struct ListNode* ret=head;
while(ret!=Slow){
ret=ret->next;
Slow=Slow->next;
if(ret->next==NULL||Slow->next==NULL){
return NULL;
}
}
return ret;
}