Advertisement
Guest User

Untitled

a guest
Feb 17th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode swapPairs(ListNode head) {
  11. if(head==null)
  12. return null;
  13. ListNode next=null;
  14. ListNode current = head;
  15. ListNode newHead = null;
  16. ListNode prev=null;
  17. next = current.next;
  18. if(next!=null) {
  19. newHead = next;
  20. }
  21. while(current!=null && next!=null) {
  22. current.next = next.next;
  23. next.next = current;
  24. //print(newHead);
  25. prev = current;
  26. current = current.next;
  27. if(current!=null)
  28. next = current.next;
  29. if(prev!=null && current!=null && next!=null) {
  30. prev.next = next;
  31. }else if(prev!=null && current!=null && next==null){
  32. prev.next=current;
  33. }
  34.  
  35.  
  36. }
  37. if(newHead !=null)
  38. return newHead;
  39. return head;
  40.  
  41. }
  42.  
  43. // void print(ListNode node){
  44.  
  45. // ListNode newNode = node;
  46. // while(newNode!=null) {
  47. // System.out.print(newNode.val+" -> ");
  48. // newNode = newNode.next;
  49. // }
  50. // System.out.println();
  51. // }
  52.  
  53.  
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement