LeetCode 2 :Swap Nodes in Pairs
2024-08-26 09:47:41
我的代码是这样的:
class Solution {
public:
ListNode *swapPairs(ListNode *head)
{
const int TRUE = ;
const int FALSE = ;
ListNode *listA;
ListNode *listB;
ListNode *listFront;
ListNode *listTail;
bool bFirstTime = TRUE; listFront = head;
while(listFront != NULL)
{ listA = listFront;
if(bFirstTime)
{
listTail = listFront;
}
listB = listFront->next;
if(!bFirstTime && listB == NULL)
{
return head;
}
if(bFirstTime && listB==NULL)
{
return listA;
}
listFront = listFront->next->next;
if(bFirstTime && listB !=NULL)
{
head = listB;
bFirstTime = FALSE;
}
if(!bFirstTime)
{
listTail->next = listB;
listTail = listA;
}
listB->next = listA;
listA->next = listFront; }
return head;
}
};
网上找的大神的代码:
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *cur = NULL, *next = NULL, *tmp = NULL, *pre = NULL;
cur = head;
if(cur != NULL && cur->next != NULL)
head = cur->next;
while(cur != NULL)
{
if(cur->next == NULL)
{
return head;
}
next = cur->next;
if(pre != NULL)
pre->next = next;
tmp = next->next;
next->next = cur;
cur->next = tmp;
pre = cur;
cur = cur->next; }
return head; }
};
这个问题主要考虑的是两个节点交换位置时,后续节点指针信息的保存。A->B->C->D,经过一次变换后B->A->C->D->E,此时不能丢失指向A的指针pTail,因为一次变换后标记指针已经移动到下一次的处理单位,即pA指向C,pB指向D,pFront指向E,第二次交换若没有pTail的变化会成为B->A->C<-D,链表丢失了D元素且交换失败。因此在第二次交换多出的步骤是将只想A的指针pTail->next = pB;pTial = pA;完成正确的首位相连。以上是一个主要的交换思路。
此外考虑的是程序的结束标志,考虑的是只有一个输入时,和若干个输入时的ptr->next的值是否是NULL,我的程序加入了一个bFirst使得考虑情况很复杂化,观察他人的代码,直接用了if(curr!=NULL && cur->next!=NULL) 来对确定为头节点,这里当只有一个节点时,它不执行。而在循环里边使用if(curr->next == NULL) 来作为结束标志return head; 程序的结构明了。其中pTail的交换如前所述。
总结:程序的结束条件,初始条件必须明了简单。
最新文章
- SQL Server Database 维护计划创建完整的备份策略
- jquery.validate remote的用法
- 在iframe中获取本iframe DOM引用
- UVALive 6577 Binary Tree 二叉树的LRU串
- Log4net介绍
- 项目重新部署后报The attribute required is undefined for the annotation type XmlElementRef
- Android Configuration change属性
- cocos2dx 帧动画(iOS)
- JSON基础学习
- UVA 10312 - Expression Bracketing(数论+Catalan数)
- Eclipse 编码区-保护色-快捷大全
- Chapter 1 First Sight——8
- 译MassTransit 快速入门
- 进程PID 与PPID
- Eclipse中java文件生成jar文件的方法
- centos7 安装oracle11g
- delphi 调用Webservice 引入wsdl 报错 document empty
- 如何利用 jQuery 修改 css 中带有 !important 的样式属性?
- 【HTML】WWW简介
- java 空语句