从今天开始刷算法题,加油!剑指offer_在线编程_牛客网
JZ6 从尾到头打印链表
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arr = new ArrayList<Integer>();
ListNode p = listNode;
ArrayList<Integer> stack = new ArrayList<Integer>();
while (p != null) {
stack.add(p.val);
p = p.next;
}
int n = stack.size();
for (int i = n - 1; i >= 0; i--) {
arr.add(stack.get(i));
}
return arr;
}
}
思路:拿一个stack来存储,实际上多此一举了。
看了题解还有更简单的方法,ArrayList本身也可以实现类似栈的功能,list.add(0, xxx)即可插入头部:
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> res = new ArrayList<Integer>();
while(listNode != null){
res.add(0,listNode.val);
listNode = listNode.next;
}
return res;
}
}
JZ24 反转链表
要求原地反转链表
思路:p用来保存当前节点head的前一个节点,q用来保存当前节点的下一个节点。
public class Solution {
public ListNode ReverseList (ListNode head) {
// write code here
if(head==null) return null;
ListNode p=null;
ListNode q=null;
while (head!= null) {
q=head.next;
head.next=p;
p=head;
head=q;
}
return p;
}
}
JZ25 合并两个排序的链表
合并两个有序链表,合并后也要有序。
思路:首先判断特殊情况(为空时),定义一个newhead=初始值最小的那个,然后h1或者h2向后移位,每次比较h1和h2的大小,谁小就连谁。最后当有一个连完了,直接把另一个整个接上就行。
public class Solution {
public ListNode Merge (ListNode pHead1, ListNode pHead2) {
// write code here
if (pHead1 == null) return pHead2;
else if (pHead2 == null) return pHead1;
else {
ListNode newhead;
if (pHead1.val < pHead2.val) {newhead = pHead1;pHead1=pHead1.next;}
else {newhead = pHead2;pHead2=pHead2.next;}
ListNode p = newhead;
while (pHead1 != null && pHead2 != null) {
if (pHead1.val < pHead2.val) {
p.next = pHead1;
p = p.next;
pHead1 = pHead1.next;
} else {
p.next = pHead2;
p = p.next;
pHead2 = pHead2.next;
}
}
if(pHead1==null) p.next=pHead2;
else p.next=pHead1;
return newhead;
}
}
}
看一下题解,贴一个递归版本写法:
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null){
return list2;
}
if(list2 == null){
return list1;
}
if(list1.val <= list2.val){
list1.next = Merge(list1.next, list2);
return list1;
}else{
list2.next = Merge(list1, list2.next);
return list2;
}
}