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; }
- * }
- */
- class Solution {
- public ListNode swapPairs(ListNode head) {
- if(head==null)
- return null;
- ListNode next=null;
- ListNode current = head;
- ListNode newHead = null;
- ListNode prev=null;
- next = current.next;
- if(next!=null) {
- newHead = next;
- }
- while(current!=null && next!=null) {
- current.next = next.next;
- next.next = current;
- //print(newHead);
- prev = current;
- current = current.next;
- if(current!=null)
- next = current.next;
- if(prev!=null && current!=null && next!=null) {
- prev.next = next;
- }else if(prev!=null && current!=null && next==null){
- prev.next=current;
- }
- }
- if(newHead !=null)
- return newHead;
- return head;
- }
- // void print(ListNode node){
- // ListNode newNode = node;
- // while(newNode!=null) {
- // System.out.print(newNode.val+" -> ");
- // newNode = newNode.next;
- // }
- // System.out.println();
- // }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement