输入一个整数,将这个整数以字符串的形式逆序输出,程序不考虑负数的情况,若数字含有0,则逆序形式也含有0,如输入为100,则输出为001
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
while(scan.hasNextInt()){
String s = scan.nextLine();
StringBuffer sb = new StringBuffer();
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
System.out.println(sb.toString());
}
}
}
接受一个只包含小写字母的字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
StringBuilder sb=new StringBuilder();
sb.append(str);
System.out.println(sb.reverse().toString());
}
}
输入一个链表,反转链表后,输出新链表的表头。
/*
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;
}
}
判断给定的链表中是否有环。如果有环则返回true,否则返回false。你能给出空间复杂度o(1)的解法么?
快慢指针的解法, 一个指针走两步 一个指针走一步,如果快指针直接到了null 说明没有环, 如果有环的话 总有一次结果会让快指针和慢指针相等。
/**
* 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) {
ListNode p = head;
ListNode q = head;
while(p!=null && p.next!=null){
p = p.next.next;
q = q.next;
if(p==q){
return true;
}
}
return false;
}
}