It's all problem about Data structure tonight.It's true easy if you understand pointer.
Notice : This artical is wrote by Flex,myself.All rights reversed.Please contact me if reproduced;
First Problem :
On this problem,We can create a new head pointer to link the reverse linked list first.then we should traverse original linked list and push every node in the new linked list by head insertion method(头插法).In the end,by invert original linked list,we can get a new linked list.that's the answer.
Following code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode p = head.next;
ListNode pr = head;
ListNode newHead = new ListNode(0);
newHead.next = null;
while(p != null) {
pr.next = null;
if(newHead.next == null) newHead.next = pr;
else {
pr.next = newHead.next;
newHead.next = pr;
}
pr = p;
p = p.next;
}
if(newHead.next == null) newHead.next = pr;
else {
pr.next = newHead.next;
newHead.next = pr;
}
return newHead.next;
}
}
Second Problem:
It's so easy problem! Just set two pointer 'p' and 'q'. 'p' use to traverse 'l1' and 'q' use to traverse 'l2'.In the begin,'p' and 'q' point the first node in their linked list.then if 'p' isn't null pointer and 'q' is also not null,we should compare their value,and choose the smaller push in the new linked list.else if 'p' is null pointer and 'q' is not a null pointer,we can just push the node pointed by 'q'.Also,we should push 'p' in the new linked list when 'p' is not null and 'q' is null.
Following code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode merge(ListNode l1, ListNode l2) {
ListNode Head = new ListNode(0);
ListNode p = l1,q = l2,l = Head;
while(p != null | q != null) {
ListNode x = new ListNode(0);
x.next = null;
if(p != null & q != null) {
if(p.val > q.val) {
x.val = q.val;
q = q.next;
} else {
x.val = p.val;
p = p.next;
}
} else if(p != null & q == null) {
x.val = p.val;
p = p.next;
} else if(p == null & q != null) {
x.val = q.val;
q = q.next;
}
l.next = x;
l = x;
}
return Head.next;
}
}