LeetCode OJ 24. 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.

Subscribe to see which companies asked this question

解答:
这道题目的话就是区分奇数个节点和偶数个节点,然后注意一下只有一个头节点、空链表的情况就好了。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
    struct ListNode *tmp, *new_head = head, *tail = NULL;

    while(NULL != head&&NULL != head->next){
        tmp = head->next;
        head->next = head->next->next;
        tmp->next = head;
        if(head == new_head){
            new_head = tmp;
        }
        else{
            tail->next = tmp;
        }
        tail = head;
        head = head->next;
    }
    if(NULL != head&&NULL != tail){
        tail->next = head;
    }
    return new_head;
}
上一篇:C++调用约定和名字约定


下一篇:寒假训练——搜索 K - Cycle