This question is a very fundamental one about manipulation of linked lists.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode preHead = new ListNode(0);
preHead.next = head;
ListNode preNode = head;
ListNode pstNode = head.next;
//swap first two
preHead.next = pstNode;
preNode.next = pstNode.next;
pstNode.next = preNode;
while(preNode.next!=null && preNode.next.next != null){
ListNode tmpPre = preNode;
preNode = preNode.next;
pstNode = preNode.next;
//swap
tmpPre.next = pstNode;
preNode.next = pstNode.next;
pstNode.next = preNode;
}
return preHead.next;
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
No comments:
Post a Comment