建站与备案的具体流程是什么,企业网站设计怎么做,百丽鞋业网站建设,asp网站发送邮件题目描述
题目链接#xff1a;206. 反转链表 - 力扣#xff08;LeetCode#xff09; 分析题目
思路一
我们可以设计算法让整个链表掉头 定义三个代码n1,n2,n3
n1指向NULL#xff0c;n2指向head#xff0c;n3指向第二个结点 当n2不为NULL的时候#xff0c;让n2-ne…题目描述
题目链接206. 反转链表 - 力扣LeetCode 分析题目
思路一
我们可以设计算法让整个链表掉头 定义三个代码n1,n2,n3
n1指向NULLn2指向headn3指向第二个结点 当n2不为NULL的时候让n2-next反方向指向n1然后n1n2n3都往后移动 当n3走到NULL的时候会出现空指针的问题这个时候我们给n3单独加一个判断
if(n3!NULL)n3n3-next
注意我们没有交换值而是改变了指针的指向
另外当链表本身为空的时候直接返回NULL所以我们也需要加一个判断链表为空的条件
思路二
定义一个newhead指向NULL作为新链表的头定义cur指向原链表的第一个结点next保存第二个结点 然后将cur尾插newhead作为新的头cur走到原链表的第二个结点next指向next-next 最后当cur不为空的时候则进入循环为了防止next成为空指针我们加一个判断
if(next!NULL)则nextnext-next
同样的当链表本身为空的时候直接返回NULL所以我们也需要加一个判断链表为空的条件
代码示例
代码一
根据思路一我们可以写出下面的代码
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
struct ListNode* reverseList(struct ListNode* head) {if(headNULL){return NULL;}struct ListNode* n1NULL;struct ListNode* n2head;struct ListNode* n3n2-next;while(n2){n2-nextn1;n1n2;n2n3;if(n3)n3n3-next;}free(n3);free(n2);return n1;
}
结果就通过了 代码二
根据思路二我们可以写出下面的代码
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
struct ListNode* reverseList(struct ListNode* head) {if(headNULL){return NULL;}struct ListNode* newheadNULL;struct ListNode* curhead;struct ListNode* nextcur-next;while(cur){cur-nextnewhead;newheadcur;curnext;if(next)nextnext-next;}free(next);free(cur);return newhead;
}
同样结果也可以通过 以上就是解这道题的两个思路