【LeetCode】Swap Nodes in Pairs

来源:互联网 发布:家用手动工具套装 知乎 编辑:程序博客网 时间:2024/05/05 23:20

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.

分析:每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */ // 时间复杂度 O(n),空间复杂度 O(1)class Solution {public:      ListNode *swapPairs(ListNode *head) {         if(nullptr==head || nullptr==head->next) return head;         ListNode init(-1);         init.next = head;                  for(ListNode *prev=&init,*cur=prev->next,*next=cur->next; next; prev=cur,cur=cur->next,next=cur?cur->next:nullptr){             prev->next = next; //把头指针设置为要交换第二个数             cur->next = next->next;// 把要交换的第一个数的next设置为第二个数的next             next->next = cur; // 把要交换的第二个数的next设置为第一个数         }         return init.next;      }};


0 0
原创粉丝点击