LeetCode 24. 两两交换链表中的节点

题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

 

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

居然一次过了

执行结果:
通过
执行用时 :0 ms, 在所有 C 提交中击败了100.00%的用户
内存消耗 :7.1 MB, 在所有 C 提交中击败了85.19%的用户
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* swapPairs(struct ListNode* head){
 9     if(head==NULL||head->next==NULL) return head;
10     struct ListNode *h=head;
11     struct ListNode *fast=h;
12     while(h&&h->next){
13         fast=h->next->next;
14         int tmp=h->val;
15         h->val=h->next->val;
16         h->next->val=tmp;
17         h=fast;
18     }
19     return head;
20 }

 

posted @ 2019-08-16 10:07  wydxry  阅读(234)  评论(0编辑  收藏  举报
Live2D