LeeCode-Swap Nodes in Pairs
2015-07-20 09:20
666 查看
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
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.
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* swapPairs(struct ListNode* head) { struct ListNode *p=head,*q=head; int LiskLen=0; while(q!=NULL) { LiskLen++; q=q->next; } if(LiskLen%2==0) { while(p!=NULL) { int temp; temp=p->val; p->val=p->next->val; p->next->val=temp; p=p->next->next; } } else { while(p->next!=NULL) { int temp; temp=p->val; p->val=p->next->val; p->next->val=temp; p=p->next->next; } } return head; }
相关文章推荐
- 理解inode
- LeeCode-Delete Node in a Linked List
- nodejs之async异步编程
- PHP vs Node.js
- NodeJS async实例详解:When to use what?
- ECMAScript 6教程 (二) 对象和函数
- Node JS文件操作fs
- Remove Nth Node From End of List
- Node JS 模块
- Permission denied: user=Administrator, access=WRITE, inode="hadoop":hadoop:supergroup:rwxr-xr-x
- Delete Node in a Linked List
- 【leetcode】Delete Node in a Linked List
- Node:Trie数(字典树)
- secondarynamenode无法启动
- node.js乱码
- 多次格式化namenode,datanode无法启动的解决办法
- #25 Reverse Nodes in k-Group
- Swap Nodes in Pairs
- node模块的载入及机制
- node及npm安装过程中的win环境变量设置