Leetcode swap-nodes-in-pairs(链表 交换相邻节点)

题目描述

将给定的链表中每两个相邻的节点交换一次,返回链表的头指针
例如,
给出1->2->3->4,你应该返回链表2->1->4->3。
你给出的算法只能使用常量级的空间。你不能修改列表中的值,只能修改节点本身。
 
 

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given1->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.

 
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        ListNode *res = new ListNode(0);
        ListNode *p=res;
        if(head==NULL||head->next==NULL)
            return head;
        ListNode *l=head;
        ListNode *r=l->next;
        while(l!=NULL&&r!=NULL)
        {
            p->next=r;
            l->next=r->next;
            r->next=l;
            p=l;
            l=p->next;
            r=l->next;
        }
        return res->next;
    }
};

猜你喜欢

转载自www.cnblogs.com/zl1991/p/12799219.html