1. 回文链表
给定一个链表的 头节点 head ,请判断其是否为回文链表。如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。
分析:
使用数组List把链表中节点的值复制,再用双指针遍历判断是否为回文。
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> vals = new ArrayList<Integer>();
// 将链表的值复制到数组中
ListNode currentNode = head;
while (currentNode != null) {
vals.add(currentNode.val);
currentNode = currentNode.next;
}
// 使用双指针判断是否回文
int front = 0;
int back = vals.size() - 1;
while (front < back) {
if (!vals.get(front).equals(vals.get(back))) {
return false;
}
front++;
back--;
}
return true;
}
}
2. 重排链表
给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln-1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
分析:
先将链表转化为数组,然后再利用双指针进行重排。
class Solution {
public void reorderList(ListNode head) {
List<ListNode> list = new ArrayList<>();
while (head != null){
list.add(head);
head = head.next;
}
int i = 0, j = list.size()-1;
while (i < j){
list.get(i).next = list.get(j);
i++;
if (i == j) break;
list.get(j).next = list.get(i);
j--;
}
list.get(i).next = null;
}
}
3. 链表中的两数相加
给定两个非空链表 l1和 l2 来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
可以假设除了数字 0 之外,这两个数字都不会以零开头。
分析:
借助栈来实现,建两个栈然后把遍历两个链表并把节点分别存入栈中,然后就是加法运算,与数组的加法运算类似。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
while (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2 != null){
stack2.push(l2.val);
l2 = l2.next;
}
int add = 0;
ListNode head = null;
while (!stack1.isEmpty() || !stack2.isEmpty() || add != 0){
int a = stack1.isEmpty()?0:stack1.pop();
int b = stack2.isEmpty()?0:stack2.pop();
ListNode node = new ListNode((a+b+add)%10);
add = (a+b+add)/10;
node.next = head;
head = node;
}
return head;
}
}
4. 反转链表
给定单链表的头节点 head ,请反转链表,并返回反转后的链表的头节点。
分析:
双指针+迭代。
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode pre = null, cur = head;
while (cur !=null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
5. 生成每种字符都是奇数个的字符串
给你一个整数 n,请你返回一个含 n 个字符的字符串,其中每种字符在该字符串中都恰好出现 奇数次 。返回的字符串必须只含小写英文字母。如果存在多个满足题目要求的字符串,则返回其中任意一个即可。
分析:
判断一下n的奇偶性,然后生成字符串。
class Solution {
public String generateTheString(int n) {
StringBuffer stringBuffer = new StringBuffer();
if (n%2 == 0){
for (int i = 0; i < n-1; i++) {
stringBuffer.append("a");
}
stringBuffer.append("b");
return stringBuffer.toString();
}
for (int i = 0; i < n; i++) {
stringBuffer.append("a");
}
return stringBuffer.toString();
}
}