206.反转链表
![](https://img-blog.csdnimg.cn/img_convert/0da9b2ea91fc4d649bc08efdd6c572e2.png)
①解决思路
方法1:使用三个指针pre,cur,next分别指向上一个节点,本节点和下一节点,每次将cur指向next的指针改成指向pre,这之后使这三指针都向后移,不断迭代得到结果。
方法2:创建一个新链表,将各个节点分别头插到新链表中,最后返回新链表。
②代码实践
方法1
struct ListNode* reverseList(struct ListNode* head)
{
struct ListNode* pre = NULL, *cur = head,*next;
if (head == NULL)
{
return NULL;
}
next = head->next;
while (cur)
{
cur->next = pre;
pre = cur;
cur = next;
if (next)
{
next = next->next;
}
}
return pre;
}
方法2
struct ListNode* reverseList(struct ListNode* head)
{
if (head == NULL)
{
return NULL;
}
struct ListNode* cur = head;
struct ListNode* newhead = NULL;
while (cur)
{
struct ListNode* next = cur->next;
//头插
cur->next = newhead;
newhead = cur;
cur =next;
}
return newhead;
}
21.合并两个有序链表
![](https://img-blog.csdnimg.cn/img_convert/336c39d135d8563a63f9b75485f70f4a.png)
题目:21. 合并两个有序链表 - 力扣(LeetCode)
①解决思路
方法1:分别比较两个链表中对应两个的值,创建一个新链表,将其中较小的值尾插到新链表上,当某一链表元素数值均插入完成时,再将另一个链表剩余的部分尾插到新链表上,最后返回新链表。
②代码实践
方法1
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
if (!list1)
{
return list2;
}
if (!list2)
{
return list1;
}
struct ListNode* cur1 = list1, *cur2 = list2, *head = NULL, *tail = NULL;
while (cur1 && cur2)
{
if(cur1->val < cur2->val)
{
if( head == NULL)
{
head = tail = cur1;
}
else
{
tail->next = cur1;
tail = tail->next;
}
cur1 = cur1->next;
}
else
{
if ( head == NULL)
{
head = tail = cur2;
}
else
{
tail->next = cur2;
tail = tail->next;
}
cur2 = cur2->next;
}
}
if (cur1)
{
tail->next = cur1;
}
if (cur2)
{
tail->next = cur2;
}
return head;
}