怎样用jsp做网站,边城网页设计素材,怎么查网站的浏览量,微商怎么做推广加好友乐观学习#xff0c;乐观生活#xff0c;才能不断前进啊#xff01;#xff01;#xff01; 我的主页#xff1a;optimistic_chen 我的专栏#xff1a;c语言 点击主页#xff1a;optimistic_chen和专栏#xff1a;c语言#xff0c; 创作不易#xff0c;大佬们点赞鼓… 乐观学习乐观生活才能不断前进啊 我的主页optimistic_chen 我的专栏c语言 点击主页optimistic_chen和专栏c语言 创作不易大佬们点赞鼓励下吧~ 文章目录 移除链表元素反转链表完结 移除链表元素
移除链表元素—力扣 第一种思路简单粗暴直接遍历一次链表把val所在的节点释放掉。
typedef struct ListNode ListNode;
struct ListNode* removeElements(struct ListNode* head, int val) {ListNode *curehead;ListNode* prevhead;while(cure){if(cure-valval){if(headcure){headcure-next;}else{prev-nextcure-next;}curecure-next;}else{prevcure;cureprev-next;}}return head;
}第二种思路创建新链表再遍历原链表找到不为 val 的节点尾插到新链表。 typedef struct ListNode ListNode;
struct ListNode* removeElements(struct ListNode* head, int val) {if (head NULL)return NULL;//创建一个新链表ListNode* newHead, * newTail;newHead newTail NULL;ListNode* pcur head;//遍历原链表while (pcur){//找不为val的节点尾插if (pcur-val ! val){//链表为空if (newHead NULL){newHead newTail pcur;}//链表不为空else{//有一个节点以上newTail-next pcur;newTail newTail-next;}}pcur pcur-next;}if (newTail)//若原链表为空判断newTail是否为空newTail-next NULL;return newHead;}
反转链表
反转链表—力扣 头插法创建一个新链表遍历原链表依次取下原链表的每一个节点头插到新链表中。 typedef struct ListNode ListNode;
struct ListNode* reverseList(struct ListNode* head) {if (head NULL)return NULL;ListNode* newHead, * newTail;newHead newTail NULL;ListNode* pcur head;//一个一个拿下来头插while (pcur){ListNode* next pcur-next;pcur-next newHead;newHead pcur;pcur next;}return newHead;
}
反转指针法定义三个变量 n1n2n3根据它们的指向关系进行迭代。
typedef struct ListNode ListNode;
struct ListNode* reverseList(struct ListNode* head) {if (head NULL)return NULL;ListNode* n1, * n2, * n3;n1 NULL, n2 head, n3 n2-next;while (n2){n2-next n1;n1 n2;n2 n3;if (n3)//别忘记判断 n3 防止对空指针解引用n3 n3-next;}return n1;
}
注 循环条件当 n2 为空时n1 指向反转后的头此时循环结束
完结
好了这期的分享到这里就结束了~ 如果这篇博客对你有帮助的话可以点一个免费的赞并收藏起来哟~ 可以点点关注避免找不到我~ 我们下期不见不散~~ 这个链表题目还会继续敬请期待~