You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
您将获得两个非空链接列表,表示两个非负整数。 数字以相反的顺序存储,并且它们的每个节点包含单个数字。 添加两个数字并将其作为链接列表返回。
您可以假定这两个数字不包含任何前导零,除了数字0本身。
输入:(2→4→3)+(5→6→4)
输出:7 - > 0 - > 8
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode node = new ListNode(0);
if(l1 == null && l2 == null) return l1;
back(node, l1, l2);
return node;
}
public void back(ListNode result, ListNode l1, ListNode l2){
if(l1 != null) result.val += l1.val;
else l1 = new ListNode(0);
if(l2 != null) result.val += l2.val;
else l2 = new ListNode(0);
ListNode node = new ListNode(0);
if(result.val >= 10){//说明会下一个节点值至少为1
result.val = result.val % 10;
node.val = 1;
result.next = node;
}
if( (l1.next != null || l2.next != null)){
result.next = node;
back(result.next, l1.next, l2.next);
}
}
}
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
意思是:去除链表中重复的部分
这里需要注意的点:
1. 如何返回链表
2. 当链表中存在3个以上相同的节点时的处理
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return null;
ListNode node = head;//1. 用一个节点来保存链头,用于返回
while(head != null){
ListNode next = head.next;
if(next != null && next.val == head.val){
head.next = next.next;
continue;//2. 当有3个以上相同的节点时,不进入下一个节点,一直到相同节点的最后那个节点时,才跳到下一个节点
}
head = head.next;
}
return node;
}
}
设计一个有最小值的Stack
可以使用链表来构造
public class MinStack {
private Node head;
public void push(int x) {
if (head == null) {
head = new Node(x, x);
} else {
head = new Node(x, Math.min(head.min, x), head);
}
}
public void pop() {
head = head.next;
}
public int top() {
return head.val;
}
public int getMin() {
return head.min;
}
private class Node {
int val;
int min;
Node next;
private Node(int val, int min) {
this(val, min, null);
}
private Node(int val, int min, Node next) {
this.val = val;
this.min = min;
this.next = next;
}
}
}