leetcode题目例题解析(七)

leetcode题目例题解析(七)

Swap Nodes in Pairs

题目描述:

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.

题意解析:

两两翻转链表,每两个相邻的链表翻转

解题思路:

就是对链表的基本操作,对链表的操作注意不要断开就可以了

代码:

/**
 * 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* loop = head;
        ListNode* temp;
        ListNode* last = NULL;
        //先处理头部
        if (head&&head->next) {
            head = head->next;
        }
        //判断是否是两个,如果剩一个,就不用再转换了
        while(loop&&loop->next) {
            if (last) {
                last->next = loop->next;
            }
            last = loop;
            temp = loop->next->next;
            loop->next->next = loop;
            loop->next = temp;
            loop = temp;
        }
        return head;
    }
};

原题目链接:
https://leetcode.com/problems/swap-nodes-in-pairs/description/

猜你喜欢

转载自blog.csdn.net/OzhangsenO/article/details/78314806
今日推荐