LeetCode:Swap Nodes in Pairs

題目連接html

Given a linked list, swap every two adjacent nodes and return its head.node

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.spa

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.code


給鏈表添加一個臨時的頭結點, 這樣操做更方便。其實大部分鏈表問題,添加一個頭結點,都會簡化後面的操做   本文地址htm

/**
 * 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) {
        ListNode tmphead(0); tmphead.next = head;
        ListNode *pre = &tmphead, *p = head;
        while(p && p->next)//p 和 p->next是待交換的兩個節點,pre是p的前一個節點
        {
            pre->next = p->next;
            p->next = p->next->next;
            pre->next->next = p;
            
            pre = p;
            p = p->next;
        }
        return tmphead.next;
    }
};

 

【版權聲明】轉載請註明出處http://www.cnblogs.com/TenosDoIt/p/3793641.htmlblog

相關文章
相關標籤/搜索