动易网络 官方网站,代做预算网站,wordpress 顶部高度,18元套餐今天讲一些关于链表的Oj题#xff0c;相信你看完对链表又提升一个档次。
题目一 思路一 遍历一遍链表是Val值得时候free这个#xff0c;然后我们往后走#xff0c;一直走到末尾空指针得时候#xff0c;新链表就是我们得答案#xff0c;那我们用代码来表示一下吧。 struct… 今天讲一些关于链表的Oj题相信你看完对链表又提升一个档次。
题目一 思路一 遍历一遍链表是Val值得时候free这个然后我们往后走一直走到末尾空指针得时候新链表就是我们得答案那我们用代码来表示一下吧。 struct ListNode* removeElements(struct ListNode* head, int val){struct ListNode*curhead;struct ListNode*preNULL;while(cur){if(cur-valval){if(preNULL){headcur-next;free(cur);curhead;}else{pre-nextcur-next;free(cur);curpre-next;}}else{precur;curcur-next;}}return head;
}思路二 不是val我们就拿下来是val就跳过放到新链表中。
struct ListNode* removeElements(struct ListNode* head, int val){struct ListNode*tailNULL;struct ListNode*curhead;headNULL;while(cur){if(cur-valval){curcur-next;}else{if(tailNULL){headtailcur;}else{tail-nextcur;tailtail-next;}curcur-next;}}if(tail)tail-nextNULL; return head;
}思路三 带哨兵位得头节点得方法是val拿下来不是跳过。 struct ListNode* removeElements(struct ListNode* head, int val){struct ListNode*curhead;head(struct ListNode*)malloc(sizeof(struct ListNode));struct ListNode*tailhead;tail-nextNULL;while(cur){if(cur-valval){struct ListNode*delcur;curcur-next;free(del);}else{tail-nextcur;curcur-next;tailtail-next;}}tail-nextNULL;struct ListNode*delhead-next;free(head);return del;}题目二 这题我们可以改变指向给三个指针变量变方向就可以解决。
struct ListNode* reverseList(struct ListNode* head){if(headNULL)return NULL;struct ListNode*curhead;struct ListNode*preNULL;struct ListNode*nextcur-next;while(cur){cur-nextpre;precur;curnext;if(next)nextnext-next;}return pre;
}思路二 头插到新链表就可以了。
struct ListNode* reverseList(struct ListNode* head){struct ListNode*curhead;struct ListNode*pheadNULL;while(cur){struct ListNode*nextcur-next;cur-nextphead;pheadcur;curnext;}return phead;
}题目三 用快慢指针快走两步慢走一步就可以解决。
struct ListNode* middleNode(struct ListNode* head){struct ListNode*slowhead;struct ListNode*fasthead;while(fast fast-next){slowslow-next;fastfast-next;if(fast)fastfast-next;}return slow;
}题目四
struct ListNode* FindKthToTail(struct ListNode* pListHead, int k ) {struct ListNode*slowpListHead;struct ListNode*fastpListHead;while((k--)){if(fastNULL)return NULL;fastfast-next;}while(fast){fastfast-next;slowslow-next;}return slow;
}这题和快慢指针差不多先让快指针走k步然后同时走结束条件就是快指为空的时候。
今天就先分享四道题目后面再继续分享几道谢谢大家观看