码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 24 -- Swap Nodes in Pairs

时间:2015-06-08 11:42:30      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:list

Swap Nodes in Pairs

题目:
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


思路:
注意保存pre先前的指针,还要注意特殊情况,有0个或者1个节点。以及链表长度为奇数的情况。


代码:

/**
 * 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) {
        //特殊情况,0个或1个节点
        if(head == NULL || head->next == NULL){
            return head;
        }
        ListNode *p = head;
        ListNode *q = head->next;
        //两个节点的情况
        if(q->next == NULL){
            q->next = p;
            p->next = NULL;
            head = q;
            return head;
        }
        ListNode *nextNode = q->next;
        ListNode *pre;
        head = q;
        while(q != NULL && nextNode != NULL){
            //改变指针指向
            pre = p;
            q->next = p;
            p->next = nextNode;
            //向前跳转
            q = nextNode->next;
            if(q == NULL){
                break;
            }
            p = nextNode;
            nextNode = q->next;
            pre->next = q;
        }
        //处理奇数节点的情况
        if(nextNode == NULL){
            pre->next = q;
            q->next = p;
            p->next = NULL;
        }
        return head;
    }
};

leetcode 24 -- Swap Nodes in Pairs

标签:list

原文地址:http://blog.csdn.net/wwh578867817/article/details/46409157

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!