单链表典型题目
链表输出
给定链表,请你每隔1个节点输出1个
如1->3->4->6->11->12
输出1->4>->11
代码
public class JumpLinkList {
static ListNode head=null;
static ListNode tail=null;
public static void main(String[] args) {
ListNode l1=new ListNode(1);
ListNode l2=new ListNode(2);
ListNode l3=new ListNode(3);
// ListNode l4=new ListNode(5);
// ListNode l5=new ListNode(6);
// ListNode l6=new ListNode(11);
l1.next=l2;
l2.next=l3;
// l3.next=l4;
// l4.next=l5;
// l5.next=l6;
create(l1);
}
public static void create(ListNode head){
ListNode cur=head;
createLink(head.val);
while (cur.next!=null &&cur.next.next!=null){
cur=cur.next.next;
createLink(cur.val);
}
}
public static ListNode createLink(int val){
ListNode node=new ListNode(val);
if(tail==null && head==null){
head=node;
tail=head;
return tail;
}
tail.next=node;
tail=tail.next;
return tail;
}
}
class ListNode{
int val;
ListNode next;
ListNode down;
public ListNode(int val) {
this.val = val;
}
}
剑指 Offer 25. 合并两个排序的链表
题目
代码
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public class Solution {
public static void main(String[] args) {
ListNode l1=new ListNode(1);
ListNode l2=new ListNode(2);
ListNode l3=new ListNode(4);
ListNode l4=new ListNode(1);
ListNode l5=new ListNode(3);
ListNode l6=new ListNode(4);
l1.next=l2;
l2.next=l3;
l4.next=l5;
l5.next=l6;
ListNode head=mergeSortList(l1,l4);
System.out.println(head);
}
public static ListNode mergeSortList(ListNode l1,ListNode l2) {
ListNode dum=new ListNode(0),cur=dum;
while (l1!=null && l2 !=null){
if(l1.val>=l2.val){
cur.next=l2;
l2=l2.next;
}else{
cur.next=l1;
l1=l1.next;
}
cur=cur.next;
}
cur.next= (l1!=null ?l1:l2);
return dum.next;
}
}
剑指 Offer 22. 链表中倒数第k个节点
题目
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode format=head,latter=head;
//让format先走k步
for(int i=0;i<k;i++){
format=format.next;
}
while(format!=null){
format=format.next;
latter=latter.next;
}
return latter;
}
}
剑指 Offer 06. 从尾到头打印链表
题目
代码
思路:利用栈的特性先进后出,压入数组,时间复杂度O(n)。空间复杂度O(n)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
//栈
Stack<ListNode> stack=new Stack<ListNode>();
ListNode temp=head;
//入栈
while(temp!=null){
stack.push(temp);
temp=temp.next;
}
//定义数组
int size=stack.size();
int[] arr=new int[size];
for(int i=0;i<size;i++){
arr[i]=stack.pop().val;
}
return arr;
}
}
剑指 Offer 141. 环形链表
题目
思路快慢指针
ListNode slow=head
ListNode fast=head.next
代码
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null){
return false;
}
ListNode slow=head;
ListNode fast=head.next;
while(slow!=fast){
if(fast==null || fast.next==null ){
return false;
}
slow=slow.next;
fast=fast.next.next;
}
return true;
}
}