Problem:
Given a linked list, swap every, 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. Modify the values in the list, only nodes itself can be changed.
Solution: Simple list pointer operation, nothing good to say, complexity O (n)
The main topic: to a linked list, requires the list of the odd number of nodes and the nodes behind it interchange, and can not change the value of the node (that is, the value of the node cannot be exchanged), space complexity is required O (1)
Java source Code (272MS):
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * listnode (int x) {val = x;}}} */public class Soluti On {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;} }
The C language source code (1MS) does not open new node memory:
/** * 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 + + source code (9MS):
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {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 source code (81MS):
# Definition for singly-linked list.# class listnode:# def __init__ (self, x): # self.val = x# Self.next = Nonec Lass Solution: # @param {ListNode} head # @return {listnode} def swappairs (self, head): p=listnode (0) C7/>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
Leetcode Swap Nodes in Pairs (C,c++,java,python)