LeetCode-24:Swap Nodes in Pairs(两两交换链表中的节点) -- Medium

题目:

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

例子:

Example 1:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list’s nodes, only nodes itself may be changed.

问题解析:

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

相似题:

  1. Reverse Nodes in k-Group

思路标签

栈的思想

解答:

  • 和第25题是相似的题目,因为链表是以k长度,这里(k=2)进行翻转,所以最后生成的链表是k大小的先进后出,则明显可以以栈的形式来实现。
  • 注意要加一个返回链表头节点的指针的指针。
  • 同时需要处理末尾最后小于k的节点。
/**
 * 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) {
        stack<ListNode*> k;
        ListNode *cur = head, *lead = new ListNode(0), *prv =lead;
        while(cur){
            if(k.size()==2){
                while(k.size()){
                    prv->next = k.top();
                    k.pop();
                    prv = prv->next;
                    prv->next = NULL;
                }
            }
            k.push(cur);
            cur = cur->next;
        }
        while(k.size()){
            prv->next = k.top();
            k.pop();
            prv = prv->next;
            prv->next = NULL;
        }
        return lead->next;
    }
};

猜你喜欢

转载自blog.csdn.net/Koala_Tree/article/details/81476772