标签:des style class blog code ext
Description:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
描述:
给出单链表,交换每一个相邻的结点后返回链表头部。
比如,给出1->2->3->4,返回2->1->4->3。
回答的算法只能够有常数级别的空间花费,也不可以改变链表中结点的值。能够改变的只有结点本身(笔者注:即结点的next指针)。
分析:
又是一道看似简单,其实很考验细节的题目。数据结构已给定,那么就按照题目的意思解决。注意单链表中的边界条件。
C++代码:
1 class Solution { 2 public: 3 ListNode *swapPairs(ListNode *head) 4 { 5 if( head == NULL ) return NULL; 6 if( head ->next == NULL ) return head; 7 8 ListNode *first = head; 9 ListNode *second = first ->next; 10 head = second; 11 12 while( (first != NULL ) && (first ->next != NULL) ) { 13 first ->next = second ->next; 14 second ->next = first; 15 16 if( first ->next != NULL ) { 17 ListNode *tmp = first; 18 first = first ->next; 19 second = first ->next; 20 if( second != NULL ) { 21 tmp ->next = second; 22 } 23 } 24 } 25 26 return head; 27 } 28 };
[LeetCode]Swap Nodes in Pairs,布布扣,bubuko.com
标签:des style class blog code ext
原文地址:http://www.cnblogs.com/TheLeaf-2010/p/3785859.html