关闭

Leetcode#24 Swap Nodes in Pairs

140人阅读 评论(0) 收藏 举报
分类:

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.

Difficulty: Medium


ListNode* swapPairs(ListNode* head) {
        ListNode* first;
        ListNode* second;
        ListNode* third;
        ListNode* temp = new ListNode(0);;
        ListNode* beg;

        if(!head || !head -> next) {
         return head;
     }
        first = head;
        beg = head->next;
        while(first &&first->next)
        {

            third = first->next->next;
            second = first->next;
            temp ->next = second;
            first->next = second->next;
            second->next = first;
             temp = first;
            first = first->next;
        }
        return beg;
    }


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32548次
    • 积分:3297
    • 等级:
    • 排名:第10655名
    • 原创:311篇
    • 转载:4篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论