24. Swap Nodes in Pairs

题目: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.

给定四个指针p1,p2,p3,p4,p1指向要转换的两个数据的前一个数据,p2,p3指向要转换的数据,p4指向需要转换的两个数据之后的那个数据。


 

p1

p2

p3

p4

 

...

2

3

4

5

...

p3的下一个指向p2,p2的下一个指向p4,p1的下一个指向p3。

直到p3位空,或者p4位空,就退出程序。


代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* swapPairs(struct ListNode* head) {
    
    struct ListNode* p1=head;
    struct ListNode* p2=head;
    struct ListNode* p3=NULL;
    struct ListNode* p4=NULL;
    
    if(head==NULL)
    {
        return NULL;
    }
    else
    {
        while(true)
    {    
        p3=p2->next;
        if(p3==NULL)
        {
            printf("p3 is NULL\n");
            return head;
        }
        else
        {
            p4=p3->next;
            
            if(p1==head)
            {
                printf("At the beginning\n");
                p3->next=p2;
                p2->next=p4;
        
                head=p3;
                p1=p2; //重要
            }
            else
            {
                p3->next=p2;
                p2->next=p4;
                p1->next=p3;
                
                p1=p2;
            }
            
            printf("p1 is %d\n",p1->val);
            printf("p2 is %d\n",p2->val);
            printf("p3 is %d\n\n",p3->val);
            
             if(p4==NULL)
             {
                 struct ListNode* t=head;
                 
                 while(!t)
                    {
                        printf("Node is %d\n",t->val);
                        t=t->next;
                    }
                    
                 printf("p4 is NULL");
                 return head;
             }
             else
             {
                 p2=p4;
             }
        }
    }
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值