LeetCode 24 Swap Nodes in Pairs (C,C++,Java,Python)
阿新 • • 發佈:2019-01-06
Problem:
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.
Solution:
題目大意:
給一個連結串列,要求將連結串列的奇數個節點和它後邊的節點進行互換,並且不能更改節點的值(也就是不能互換節點的值),空間複雜度要求為O(1)Java原始碼(272ms):
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode swapPairs(ListNode head) { ListNode p=new ListNode(0),s; p.next=head; head=p; while(p.next!=null && p.next.next!=null){ s=p.next.next; p.next.next=s.next; s.next=p.next; p.next=s; p=s.next; } return head.next; } }
C語言原始碼(1ms)不開闢新的節點記憶體:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* swapPairs(struct ListNode* head) { struct ListNode *p=head,*s; if(p!=NULL && p->next!=NULL){ s=p->next; p->next=s->next; s->next=p; head=s; while(p->next!=NULL && p->next->next!=NULL){ s=p->next->next; p->next->next=s->next; s->next=p->next; p->next=s; p=s->next; } } return head; }
C++原始碼(9ms):
/**
* 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 *p,*s;
p=new ListNode(0);
p->next=head;
head=p;
while(p->next!=NULL && p->next->next!=NULL){
s=p->next->next;
p->next->next=s->next;
s->next=p->next;
p->next=s;
p=s->next;
}
return head->next;
}
};
Python原始碼(81ms):
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def swapPairs(self, head):
p=ListNode(0)
p.next=head;head=p
while p.next!=None and p.next.next!=None:
s=p.next.next
p.next.next=s.next
s.next=p.next
p.next=s
p=s.next
return head.next