题目描述
输入一个链表,反转链表后,输出新链表的表头。
代码实现
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode prior = null;
ListNode now = head;
if(head == null)
return head;
while(now != null){
ListNode next = now.next;
now.next = prior;
prior = now;
now = next;
}
return prior;
}
}
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路
先确定头节点,之后根据两个链表第一个节点的大小,按照顺序连接即可。
代码实现
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null) return list2;
if(list2 == null) return list1;
ListNode listhead = null;
if(list1.val < list2.val){
listhead = new ListNode(list1.val);
list1 = list1.next;
}else{
listhead = new ListNode(list2.val);
list2 = list2.next;
}
ListNode p = listhead;
while(list1!=null && list2.next!=null){
if(list1.val<list2.val){
ListNode newnode = new ListNode(list1.val);
list1 = list1.next;
p.next = newnode;
p = newnode;
}else{
ListNode newnode = new ListNode(list2.val);
list2 = list2.next;
p.next = newnode;
p = newnode;
}
}
while(list1!=null){
ListNode newnode = new ListNode(list1.val);
list1 = list1.next;
p.next = newnode;
p = newnode;
}
while(list2!=null){
ListNode newnode = new ListNode(list2.val);
list2 = list2.next;
p.next = newnode;
p = newnode;
}
return listhead;
}
}