[LeetCode]Swap Nodes in Pairs

本文提供了一种在C++中交换单链表中每两个相邻节点的方法,通过迭代和调整节点引用实现了链表的修改,确保了常数级别的空间复杂度,且不改变节点值。

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 };

 

转载于:https://www.cnblogs.com/TheLeaf-2010/p/3785859.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值