码迷,mamicode.com
首页 > 其他好文 > 详细

两两交换链表的结点

时间:2015-02-17 11:43:18      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

题目:

例如链表为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;
}


 

两两交换链表的结点

标签:

原文地址:http://blog.csdn.net/yuanwei1314/article/details/43865499

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!