Given a linked list, swap every two adjacent nodes and return its head.
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.
A:
就是用两个指针,每次指两个。-----recursive
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode header = new ListNode(0);
header.next = head;
helper(header);
return header.next;
}
private void helper(ListNode header){
if(header.next == null || header.next.next == null)
return;
ListNode n1 = header.next;
ListNode n2 = n1.next;
ListNode newHead = n2.next;
header.next = n2;
n2.next = n1;
n1.next = newHead;
helper(n1);
}
}
---------------- 3 rd pass---------- same as above-----but iterativepublic class Solution {
public ListNode swapPairs(ListNode head) {
ListNode header = new ListNode(0);
ListNode tail = header;
ListNode p1,p2;
while(head != null){
p1 = head;
head = head.next;
if(head!=null){
p2=head;
head = head.next;
tail.next = p2;
tail = tail.next;
}
tail.next = p1;
tail = tail.next;
tail.next = null;
}
return header.next;
}
}
忘记了把tail的next指向null。
No comments:
Post a Comment