leetcode--Swap Nodes in Pairs

来源:互联网 发布:mac安装oracle 11g 编辑:程序博客网 时间:2024/06/04 17:58

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.

解题思路

成对调换链表中的元素。
方法一:
我们直接换掉两个相邻节点的val属性即可。但是题目要求You may not modify the values in the list,虽然如此,我还是实现了这样的算法,简单快捷,为什么不呢。
class Solution {public:    ListNode* swapPairs(ListNode* head) {        if(head==NULL) return NULL;        if(head->next==NULL) return head;        ListNode* p=head,*s;        int flag=0;        while(p&&p->next)        {            s=p->next;            int temp=p->val;            p->val=s->val;            s->val=temp;            p=s->next;        }        return head;    }};

方法二

因为不能直接交换两个节点的值,只能改变节点的next,我们仿照方法一,继续交换,不过是通过改变next来实现的,代码如下。
class Solution {public:    ListNode* swapPairs(ListNode* head) {        if(head==NULL) return NULL;        if(head->next==NULL) return head;        ListNode* addNode=new ListNode(0);//为了让头结点跟其他节点一样,同样处理,增加一个节点指向头结点。        addNode->next=head;        ListNode *cur;        for(cur=addNode;cur->next!=NULL&&cur->next->next!=NULL;cur=cur->next->next)        {            cur->next=swap(cur->next,cur->next->next);        }        head=addNode->next;        return head;    }    ListNode* swap(ListNode* p,ListNode* q)    {        p->next=q->next;        q->next=p;        return q;    }};



0 0
原创粉丝点击