Record brushing questions-(leetcode-24 pairs of exchange linked list nodes)

**Question: Given a linked list, exchange adjacent nodes in it two by one, and return the exchanged linked list.
You can't just simply change the internal value of the node, but need to actually exchange the node.

Example:
Given 1->2->3->4, you should return 2->1->4->3.
Source: LeetCode
link: https://leetcode-cn.com/problems/ The
copyright of swap-nodes-in-pairs belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source. **
Idea: Create a new head pointer for the linked list.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* swapPairs(struct ListNode* head){
    
    
    struct ListNode *p=NULL,*pnext=NULL;
    if(!head)
        return head;
    if(head!=NULL){
    
    
        struct ListNode *front_head = (struct ListNode*)malloc(sizeof(struct ListNode));
        front_head->next=head;
    p=front_head;
    while(p->next!=NULL&&p->next->next!=NULL){
    
    
        pnext=p->next;
        p->next=pnext->next;
        pnext->next=pnext->next->next;
        p->next->next=pnext;
        p=pnext;
    }
    return front_head->next;
    }
    return;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/lthahaha/article/details/106441066