两两交换链表的结点

本文介绍了链表中相邻节点交换的算法实现过程,通过直接交换节点的方式,演示了如何在链表中进行节点位置互换操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

例如链表为1-->2-->3-->4,则交换后为:2-->1-->4-->3

 

代码:

 

#include <stdio.h>
#include <stdlib.h>

typedef struct ListNode
{
    ListNode* next;
    int val;
};

ListNode* swapNodeInPair(ListNode* head)
{
   /*思路:直接交换*/
   ListNode stHead = {0};
   ListNode* pre;
   ListNode* cur;
   ListNode* next;
   
   stHead.next = head;
   pre = &stHead;
   cur = stHead.next;
   
   while (cur->next)
   {
       next = cur->next;
       cur->next = next->next;
       pre->next = next;
       next->next = cur;
       pre = cur;
       cur = cur->next; /*这里要注意,由于交换后,其实就跳过两个结点*/
   }
   
   return stHead.next;
}

void createList(ListNode* head, int* num, int n)
{
     ListNode* p;
     int i;

     for (i=0; i<n; i++)
     {
        p = (ListNode*)malloc(sizeof(ListNode));
        p->next = head->next;
        p->val = num[i];
        head->next = p;
     }
}

void printList(ListNode* head)
{
   ListNode* p = head->next;

   while (p)
   {
        printf("%d ", p->val);
        p = p->next;
   }

   printf("\n");
}

int main()
{
     ListNode stHead = {0};
     int a[] = {5, 4, 3, 2, 1};
     createList(&stHead, a, 5);
     printList(&stHead);
     stHead.next = swapNodeInPair(stHead.next);
     printList(&stHead);
     return 0;
}


 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值