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.



<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"># Definition for singly-linked list.</span></p># class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self, head):
        if head==None or head.next==None:
            return head
        
        prehead = ListNode(0)
        prehead.next = head
        
        pre,cur= prehead,head
        temp = cur.next
        while True:
            cur.next = temp.next
            pre.next = temp
            temp.next = cur
            
            if cur.next==None or cur.next.next==None:
                break
            else:
                pre,cur = pre.next.next,cur.next
                temp = cur.next
        
        return prehead.next


c++

/**
 * 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* prehead = new ListNode(0);
       prehead->next = head;
       
       ListNode* pre = prehead;
       ListNode* cur = head;
       ListNode* temp = cur->next;
       while (true){
           cur->next = temp->next;
           pre->next = temp;
           temp->next = cur;
           
           if (cur->next==NULL || cur->next->next==NULL){
               break;
           }else{
               pre = pre->next->next;
               cur = cur->next;
               temp = cur->next;
           }
       }
       
       return prehead->next;
            
    }
};


你可能感兴趣的:(LeetCode)