Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 24. Swap Nodes in Pairs #6

Open
Animenzzzz opened this issue Jul 14, 2019 · 0 comments
Open

[LeetCode] 24. Swap Nodes in Pairs #6

Animenzzzz opened this issue Jul 14, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

Description

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

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:

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

解题思路:这题比较简单,画图做好每个指针的指向就好了,别丢失了指针,这题还可用递归处理,参考 grandyang/leetcode#24

C解题:

struct ListNode* swapPairs(struct ListNode* head){
    struct ListNode* current = head;
    struct ListNode* current_prefix;
    struct ListNode* result = NULL;
    while (current)
    {
        if (!head->next) break;
        if(!result){//头结点的处理
            result = head->next;
            head->next = head->next->next;
            result->next = head;
        }else{
            if(current->next){
                current_prefix->next = current->next;
                current->next = current->next->next;
                current_prefix->next->next = current;
            }
        }
        current_prefix = current;
        current = current -> next;
    }
    if(!result) return head;
    return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant