Swap Nodes in Pairs
来源:互联网 发布:淘宝店怎么刷钻 编辑:程序博客网 时间:2024/05/16 08:28
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *swapPairs(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *trueHead = head->next; ListNode *temp1 = head->next; head->next = head->next->next; temp1->next = head; while(true) { if(head->next == NULL || head->next->next == NULL) return trueHead; ListNode *pre = head; head = head->next; temp1 = head->next; pre->next = head->next; head->next = head->next->next; temp1->next = head; } }};
题目很简单,主要的障碍可能集中在,需要区别对待前两个节点和后面节点的处理,
第一个节点由于没有节点指向它,因此直接交换1、2节点的next指向就行,而后面的节点,由于每一个都有前继节点,需要前继节点
的next指向也需要改变
0 0
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- 阿里面试总结
- xcode更新到5.1,"__curl_rule_01__' declared as an array with a negative size"
- HDOJ 3065 病毒侵袭持续中
- 分别用数组和链表实现堆
- Java命名约定
- Swap Nodes in Pairs
- Windbg调试异常
- hdu 1012 u Calculate e
- Week 7 lianxi
- week7_3
- linux命令(四):分析开机内核信息 dmesg
- hdu 2212 数学问题
- 字符串Hash函数
- AOJ-AHU-OJ-13(POJ-1056) IMMEDIATE DECODABILITY