LeetCode算法系列:24. Swap Nodes in Pairs

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/81983642

题目描述:

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

Example:

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.

算法实现:

这个问题比较简单,只需要定义三个指针扫描链表即可,其中两个指向当前要交换的指针,另一个要指向这两个指针的前一个指针,因为要将其重新链接到前一个指针上

/**
 * 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) {
        if(head == NULL || head -> next == NULL)return head;
        ListNode* f = head, *b = head -> next, *p;
        f -> next = b -> next;
        b -> next = f;
        head = b;
        
        while(f -> next != NULL && f -> next -> next != NULL){
            p = f;
            f = f -> next;
            b = f -> next;
            
            p -> next = b;
            f -> next = b -> next;
            b -> next = f;
        }
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/81983642