leetcode刚入门求解
为什么会出现图中问题?如何解决?谢谢!🙏
你想一下匹配到倒数第二个会发生什么
你应该比较当前节点的数据而不是下一个的
【以下回答由 GPT 生成】
抱歉,作为语言模型,我无法提供任何个人经验或情感。我可以提供一些常见的链表问题以及解决方法,请选择你感兴趣的问题进行解答:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解决方案: 使用三个指针prev, curr, next分别表示前一个节点、当前节点和下一个节点,将当前节点指向前一个节点,然后依次向后遍历即可。代码如下:
def reverseList(head):
if not head or not head.next:
return head
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
输入: 1->2->4, 1->3->4
输出: 1->1->2->3->4->4
解决方案: 使用一个新的头节点和一个指针cur分别指向两个链表的头节点。遍历两个链表,比较当前节点值的大小,将较小的节点加入到新链表末尾,并将指针cur指向下一个节点,直到其中一个链表遍历完毕。再将剩余的链表直接拼接到新链表的末尾。代码如下:
def mergeTwoLists(l1, l2):
dummy = ListNode(0)
cur = dummy
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 if l1 else l2
return dummy.next
如果你有其他具体的链表问题或者其他类型的问题,也欢迎提供更多的信息,我将尽力给出解决方案。
【相关推荐】
修改如下,供参考:
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* ph = head, * prt = NULL;
if (head == NULL) return NULL;
while (ph) {
if (ph->val == val) {
if (ph == head)
head = ph->next;
else
prt->next = ph->next;
free(ph);
if (prt)
ph = prt->next;
else
ph = head;
}
else {
prt = ph;
ph = ph->next;
}
}
return head;
}