题目描述
输入一个链表,反转链表后,输出新链表的表头。
输入
{1,2,3}
返回值
{3,2,1}
题解
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode ReverseList(ListNode head) {
//判断链表为空或长度为1的情况
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;//pre向右走
head = next;//当前节点继续向右走
}
return pre;
}
}
解析
以3个节点为例:a b c
用pre记录当前节点的前一个节点
用next记录当前节点的后一个节点
题目描述
判断给定的链表中是否有环。如果有环则返回true,否则返回false。
你能给出空间复杂度的解法么?
题解
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null)
return false;
//快慢两个指针
ListNode slow = head;
ListNode fast = head;
while(fast!=null && fast.next!=null){
//慢指针每次走一步
slow = slow.next;
//快指针每次走两步
fast=fast.next.next;
//如果相遇,说明有环,直接返回true
if(slow==fast)
return true;
}
//否则就是没环
return false;
}
}
解析
快慢指针,慢指针针每次走一步,快指针每次走两步,如果相遇就说明有环,如果有一个为空说明没有环。
题目描述
给定一个数组,找出其中最小的K个数。例如数组元素是4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。如果K>数组的长度,那么返回一个空的数组
输入
[4,5,1,6,2,7,3,8],4
返回值
[1,2,3,4]
题解
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
if(k>input.length){
return new ArrayList();
}
ArrayList<Integer> output = new ArrayList();
while(k>0){
int sign=999;
int m=0;
for(int i=0;i<input.length;i++){
if(sign>input[i]) {
sign = input[i];
m = i;
}
}
input[m]=9999;
output.add(sign);
k--;
}
return output;
}
}
原文:https://www.cnblogs.com/1ldk/p/14633874.html