Swap Nodes in Pairs

来源:互联网 发布:算法导论视频 百度网盘 编辑:程序博客网 时间:2024/04/29 21:00

题目:

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 as2->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.


思路:

两两进行,交换,注意设定好交换节点,防止链表断裂,或是采用递归形式


代码:

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 *first=head;ListNode *pre=head;;        ListNode *second;second=first->next;//单独处理头结点first->next=second->next;second->next=first;head=second;pre=first;first=first->next;while(first!=NULL&&first->next!=NULL)//注意&&的前后顺序{second=first->next;    first->next=second->next;    second->next=first;pre->next=second;    pre=first;    first=first->next;}return head;    }ListNode *swapPairs2(ListNode *head) //递归法,清晰明了    {        if(!head) return NULL;        if(head->next)        {            ListNode *temp = head, *nextHead = head->next->next;            head = head->next;            head->next = temp;            head->next->next = swapPairs(nextHead);        }        return head;    }};


0 0
原创粉丝点击