首页 > 学院 > 开发设计 > 正文

LeetCode 24. Swap Nodes in Pairs

2019-11-08 03:16:28
字体:
来源:转载
供稿:网友

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.

answer:

class Solution {public:    ListNode* swapPairs(ListNode* head) {        ListNode* first = head;        ListNode* second ;        if(first == NULL) return head;        second = first->next;        int temp;        while(second != NULL){            temp = first->val;            first->val = second->val;            second->val = temp;            first = (first->next)->next;            if(first == NULL) return head;            second = first->next;        }        return head;    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表