-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswap_pair_node.java
More file actions
56 lines (53 loc) · 1.53 KB
/
swap_pair_node.java
File metadata and controls
56 lines (53 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
ListNode pre=d,cur=head;
while(cur!=null&&cur.next!=null) { 1,2 1,2,3
pre.next=cur.next;
cur.next=pre.next.next;
pre.next.next=cur;
pre=cur;
cur=cur.next; // cur might be null
}
return d.next;
public class Solution {
public ListNode swapPairs(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head==null||head.next==null) return head;
ListNode d=new ListNode(1);
d.next=head;
ListNode pre=d,cur=head,next=head.next;
while(cur!=null&&cur.next!=null) {
cur.next=next.next;
next.next=cur;
pre.next=next;
pre=cur;
cur=cur.next;
if(cur!=null) next=cur.next;
}
return d.next;
}
}
public class Solution {
public ListNode swapPairs(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head==null||head.next==null) return head;
ListNode p=null,pre=head,cur=head.next,next=cur.next;
int ind=1;
while(cur!=null) {
if(ind%2!=0) {
cur.next=pre;
pre.next=next;
if(p!=null) p.next=cur;
if(ind==1) head=cur;
}
else {
p=pre;
pre=cur;
}
ind++;
cur=next;
if(next!=null) next=next.next;
}
return head;
}
}