JZ3从尾到头打印链表
题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
示例1
输入
{67,0,24,58}
返回值
[58,24,0,67]
分析:
方法1:使用栈,先进后出
方法2: 使用递归
方法3:add(index:0,val)
代码:
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Test3 {
/**
* 1.栈 + ArrayList
*/
public ArrayList<Integer> printListFromTailToHead1(ListNode listNode) {
ArrayList<Integer> arrayList = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
while (listNode!=null){
stack.push(listNode.val);
listNode = listNode.next;
}
while (!stack.empty()){
arrayList.add(stack.pop());
}
return arrayList;
}
/**
* 2.递归
*/
ArrayList<Integer> list = new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
if(listNode != null){
printListFromTailToHead(listNode.next);
list.add(listNode.val);
}
return list;
}
/**
* 3.add(index:0,val)
*/
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arrayList = new ArrayList<>();
while (listNode!=null){
arrayList.add(0,listNode.val);
listNode = listNode.next;
}
return arrayList;
}
}
JZ14链表中倒数第k个节点
题目描述
输入一个链表,输出该链表中倒数第k个结点。
如果该链表长度小于k,请返回空。
示例1
输入
{1,2,3,4,5},1
返回值
{5}
分析:
参考:牛客网@数据结构和算法
“双指针法”:使用两个指针,第一个指针先移动k步,然后第二个指针再从头开始,这个时候这两个指针同时移动,当第一个指针到链表的末尾的时候,返回第二个指针即可。注意,如果第一个指针还没走k步的时候链表就为空了,我们直接返回null即可。
代码:
public ListNode FindKthToTail1 (ListNode pHead, int k) {
// write code here
ListNode first = pHead;
ListNode last = pHead;
for (int i = 0; i < k; i++) {
if(first == null) return first;
first = first.next;
}
while (first!=null){
first = first.next;
last = last.next;
}
return last;
}
方法2:使用栈解决
public ListNode FindKthToTail (ListNode pHead, int k) {
// write code here
ListNode cur = pHead;
Stack<ListNode> stack = new Stack<>();
while(cur!=null){//链表节点压栈
stack.push(cur);
cur = cur.next;
}
if(k>stack.size()||k==0){
return null;
}
//出栈的时候串成新链表
ListNode firstNode = stack.pop();
while(k-1>0){
ListNode t = stack.pop();
t.next = firstNode;
firstNode = t;
k--;
}
return firstNode;
}
JZ15反转链表
题目描述
输入一个链表,反转链表后,输出新链表的表头。
示例1
输入
{1,2,3}
返回值
{3,2,1}
分析:
***参考:***牛客网@伊万夫斯基
代码:
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode pre = null;
ListNode next = null;
while(head!=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
JZ16合并两个排序的链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
示例1
输入
{1,3,5},{2,4,6}
返回值
{1,2,3,4,5,6}
分析:
看代码吧
代码:
/**
* //定义一个head,返回head.next
*/
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode head = new ListNode(-1);
ListNode cur = head;
while(list1 != null && list2 !=null){
if(list1.val<=list2.val){
cur.next = list1;
list1 = list1.next;
}else{
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
if(list1!=null) cur.next = list1;
if(list2!=null) cur.next = list2;
return head.next;
}