24. Swap Nodes in Pairs

原创 2016年08月30日 12:00:25

这里写图片描述

这道题是25题的简化版,只要两两调换下值就可以了

#include<stdio.h>
#include<stdlib.h>
struct ListNode {
    int val;
    struct ListNode *next;
};
typedef struct ListNode * Node;
struct ListNode* swapPairs(struct ListNode* head) 
{
    Node start,mid,end;
    int temp;
    if(NULL==head||NULL==head->next)
        return head;
    start=head;
    mid=start->next;
    while(mid)
    {
        end=mid->next;
        temp=start->val;//调换
        start->val=mid->val;
        mid->val=temp;
        if(!end)
            break;
        start=end;//指针向后移
        mid=start->next;
    }
    return head;
}
int main()
{
    Node L,p,q;
    int N,i,x;
    scanf("%d",&N);
    L=malloc(sizeof(struct ListNode));
    L->next=NULL;
    p=L;
    for(i=0;i<N;i++)
    {
        scanf("%d",&x);
        q=malloc(sizeof(struct ListNode));
        q->val=x;
        q->next=NULL;
        p->next=q;
        p=q;
    }
    L=swapPairs(L->next);
    while(L)
    {
        printf("%d ",L->val);
        L=L->next;
    }
    return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode之24----Swap Nodes in Pairs

题目: Given a linked list, swap every two adjacent nodes and return its head. For example, Gi...

[leetcode: Python]24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.For example, Given 1->2->3->...
  • NXHYD
  • NXHYD
  • 2017年05月19日 15:37
  • 194

leetcode-24 Swap Nodes in Pairs

问题描述地址:https://leetcode.com/problems/swap-nodes-in-pairs/ 描述: Given a linked list, swap every two...

[24] Swap Nodes in Pairs

交换一个单项链表中相邻的元素,且不使用多余的空间,只操作单向链表中的节点指针。...
  • camlot_
  • camlot_
  • 2016年06月28日 13:21
  • 159

LeetCode OJ-24-Swap Nodes in Pairs

题目:Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2...

LeetCode24. Swap Nodes in Pairs

LeetCode24. Swap Nodes in Pairs

( Leetcode 24) Swap Nodes in Pairs

题目:Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and return its head. ...

24. Swap Nodes in Pairs [easy] (Python)

题目链接https://leetcode.com/problems/swap-nodes-in-pairs/题目原文 Given a linked list, swap every two adj...

LeetCode 24. Swap Nodes in Pairs 解题报告

LeetCode 24. Swap Nodes in Pairs 解题报告题目描述Given a linked list, swap every two adjacent nodes and retu...

leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法

Swap Nodes in Pairs  Given a linked list, swap every two adjacent nodes and return its head. F...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:24. Swap Nodes in Pairs
举报原因:
原因补充:

(最多只允许输入30个字)