Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int x) { val = x; }
- * }
- */
- public class Solution {
- public ListNode swapPairs(ListNode head) {
- if(head==null || head.next==null){
- return head;
- }
- ListNode f = head;
- ListNode s = head.next;
- ListNode last = head;
- while(f!=null && s!=null){
- //swap nodes
- ListNode temp = s.next;
- s.next = f;
- f.next = temp;
- if(last==head){
- head = s;
- }
- else{
- last.next = s;
- }
- if (temp==null){
- return head;
- }
- else{
- f = temp;
- s = temp.next;
- last = f;
- }
- }
- return head;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement