Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9f73ef6

Browse files
author
applewjg
committed
Intersection of Two Linked Lists
Change-Id: Ia79522dba80f8a1c973c17c2dd7a35617ed0dc57
1 parent28021f4 commit9f73ef6

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

‎IntersectionOfTwoLinkedLists.java

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Nov 28, 2014
4+
Problem: Intersection of Two Linked Lists
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
7+
8+
Notes:
9+
Write a program to find the node at which the intersection of two singly linked lists begins.
10+
Hints:
11+
If the two linked lists have no intersection at all, return null.
12+
The linked lists must retain their original structure after the function returns.
13+
You may assume there are no cycles anywhere in the entire linked structure.
14+
Your code should preferably run in O(n) time and use only O(1) memory.
15+
16+
17+
Solution: Two iteration.
18+
*/
19+
/**
20+
* Definition for singly-linked list.
21+
* public class ListNode {
22+
* int val;
23+
* ListNode next;
24+
* ListNode(int x) {
25+
* val = x;
26+
* next = null;
27+
* }
28+
* }
29+
*/
30+
publicclassSolution {
31+
publicListNodegetIntersectionNode(ListNodeheadA,ListNodeheadB) {
32+
ListNodecur =headA;
33+
intlenA =0,lenB =0;
34+
while (cur !=null) {
35+
++lenA;
36+
cur =cur.next;
37+
}
38+
cur =headB;
39+
while (cur !=null) {
40+
++lenB;
41+
cur =cur.next;
42+
}
43+
if (lenA >=lenB) {
44+
intdiff =lenA -lenB;
45+
while (diff >0) {
46+
headA =headA.next;
47+
--diff;
48+
}
49+
while (headA !=null &&headB !=null) {
50+
if(headA ==headB) {
51+
returnheadA;
52+
}
53+
headA =headA.next;
54+
headB =headB.next;
55+
}
56+
}else {
57+
intdiff =lenB -lenA;
58+
while (diff >0) {
59+
headB =headB.next;
60+
--diff;
61+
}
62+
while (headA !=null &&headB !=null) {
63+
if(headA ==headB) {
64+
returnheadA;
65+
}
66+
headA =headA.next;
67+
headB =headB.next;
68+
}
69+
}
70+
returnnull;
71+
}
72+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp