1.链表相交
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
解析
先获取两个链表的长度,然后移动长链表的指针次数为两个链表长度的差,最后一起移动两个链表的指针并比较是否相同,相同则返回相同的节点,到底都没有相同节点,则返回null。时间复杂度发O(n),空间复杂度O(1)。
代码
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int indexA=0;
int indexB=0;
ListNode curA=headA;
ListNode curB=headB;
while (curA!=null){
indexA++;
curA=curA.next;
}
while (curB!=null){
indexB++;
curB=curB.next;
}
curA= indexA>indexB?headA:headB;
curB= curA==headA?headB:headA;
int big= indexA>indexB?indexA:indexB;
int small= indexA>indexB?indexB:indexA;
int interval= big-small;
while (interval-->0){
curA=curA.next;
}
while (curA!=null&&curB!=null){
if (curA==curB)
return curA;
curA=curA.next;
curB=curB.next;
}
return null;
}
2.两数相加
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
代码
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> listNodes1 = new Stack<>();
Stack<Integer> listNodes2 = new Stack<>();
Stack<Integer> jg = new Stack<>();
while (l1 != null) {
listNodes1.add(l1.val);
l1 = l1.next;
}
while (l2 != null) {
listNodes2.add(l2.val);
l2 = l2.next;
}
int ident = 0;
while (listNodes1.size() != 0 || listNodes2.size() != 0) {
int i = (listNodes1.size() == 0 ? 0 : listNodes1.pop()) + (listNodes2.size() == 0 ? 0 : listNodes2.pop());
if (i > 9) {
jg.add((i + ident) % 10);
ident = 1;
} else {
jg.add((i + ident) % 10);
if (i + ident<10){
ident=0;
}
}
}
if (ident == 1) {
jg.add(1);
}
ListNode listNode = new ListNode(jg.pop());
ListNode l3 = listNode;
while (jg.size() != 0) {
l3.next = new ListNode(jg.pop());
l3 = l3.next;
}
return listNode;
}
3.反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
代码
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
ListNode newHead = null;
while (cur != null) {
ListNode curNext = cur.next;
if (curNext == null) {
newHead = cur;
}
cur.next = prev;
prev = cur;
cur = curNext;
}
return newHead;
}
题目来源:力扣(LeetCode)