我的代码是这样的:

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的交换如前所述。

总结:程序的结束条件,初始条件必须明了简单。

最新文章

  1. SQL Server Database 维护计划创建完整的备份策略
  2. jquery.validate remote的用法
  3. 在iframe中获取本iframe DOM引用
  4. UVALive 6577 Binary Tree 二叉树的LRU串
  5. Log4net介绍
  6. 项目重新部署后报The attribute required is undefined for the annotation type XmlElementRef
  7. Android Configuration change属性
  8. cocos2dx 帧动画(iOS)
  9. JSON基础学习
  10. UVA 10312 - Expression Bracketing(数论+Catalan数)
  11. Eclipse 编码区-保护色-快捷大全
  12. Chapter 1 First Sight——8
  13. 译MassTransit 快速入门
  14. 进程PID 与PPID
  15. Eclipse中java文件生成jar文件的方法
  16. centos7 安装oracle11g
  17. delphi 调用Webservice 引入wsdl 报错 document empty
  18. 如何利用 jQuery 修改 css 中带有 !important 的样式属性?
  19. 【HTML】WWW简介
  20. java 空语句

热门文章

  1. Python 3基础教程19-模块导入语法
  2. Django数据模型--表关系(一对多)
  3. Python杂篇
  4. RxJS &amp; Angular
  5. Github &amp; DMCA Takedown Policy
  6. 【Python】Linux crontab定时任务配置方法(详解)
  7. 【bzoj2287】[POJ Challenge]消失之物 背包dp
  8. MD5算法解析
  9. Spring随笔 —— IOC配置的三种不同方式简介
  10. 新手如何更换自己喜欢的背景以及此背景的css码