Lexi's Leetcode solutions

[leetcode] Merge two sorted lists | 缝起来两个排好序的linked lists

Posted on: August 1, 2013

这题的要点在于要求inplace,即不能生成一个新list然后把当前最小的加后面。所以要zig zag的缝起来,不过也不难。list的题在所有循环处把null pointer exception处理好就行了。

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  ListNode small, big, prevSmall = null;
  small = l1.val < l2.val ? l1 : l2;
  big = l1.val < l2.val ? l2 : l1;
  ListNode result = small;
  while (small != null && big != null) {
    while (small != null && small.val <= big.val) {
      prevSmall = small;
      small = small.next;
    }
  prevSmall.next = big;
  swap(small, big);
  }
  return result;
}
Tags: ,

1 Response to "[leetcode] Merge two sorted lists | 缝起来两个排好序的linked lists"

这个,绕了

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog Stats

  • 222,235 hits
August 2013
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
%d bloggers like this: