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.
思路一: 把奇数节点和偶数节点分别保存到链表
注意事项: 注意处理每条链表的尾部节点,保证链表的独立性;另外过程遍历节点时,要注意每个前后节点之间的关系
JAVA 代码:
- public ListNode swapPairs(ListNode head) {
- if(head==null || head.next==null) return head;
- ListNode one = head;
- ListNode two = head.next;
- ListNode f1 = head;
- ListNode f2 = head.next;
- ListNode p = f2.next;
- while(p!=null) {
- f1.next=p;
- f1=f1.next;
- p=p.next;
- if(p!=null) {
- f2.next=p;
- f2=f2.next;
- p=p.next;
- }
- }
- f1.next=null;
- f2.next=null; // 得到奇数链表节点和偶数链表节点,并处理尾部节点的next指针
- //one two linklist<ListNode>
- ListNode dummy = new ListNode(0);
- ListNode tail = dummy;
- while(two!=null && one!=null) {
- tail.next=two;
- tail=tail.next;
- two=two.next; // remember the tail points to a object same with two
- tail.next=one;
- tail=tail.next;
- one=one.next;
- }
- if(one!=null) tail.next=one;
- return dummy.next;
- }
思路二: 用三个指针指向pre、first、second节点,然后交换first和second节点的内容,遍历一次即可
C++代码:
- ListNode *swapPairs(ListNode *head) {
- if(head==NULL || head->next==NULL) return head;
- ListNode *dummy = new ListNode(-1);
- dummy->next=head;
- ListNode *pre=dummy;
- ListNode *f1=head;
- ListNode *s1 = head->next;
- int cn=2;
- while(s1!=NULL) {
- if(cn%2==0) {
- f1->next=s1->next;
- s1->next=f1;
- pre->next=s1;
- pre=f1;
- f1=pre->next;
- cn=0;
- s1=pre;
- }
- s1=s1->next;
- cn++;
- }
- return dummy->next;
- }

浙公网安备 33010602011771号