首页 > 代码库 > LeetCode--链表

LeetCode--链表

19. Remove Nth Node From End of List 

技术分享
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode removeNthFromEnd(ListNode head, int n) {
11         if (head == null || head.next == null) {
12             return null;
13         }
14         ListNode start = new ListNode(0); //学会保存链表的头
15         start.next = head;
16         ListNode slow = start;
17         ListNode fast = start;
18         for (int i = 0; i <= n; i++) {
19             fast = fast.next;
20         }
21         while (fast != null) {
22             slow = slow.next;
23             fast = fast.next;
24         }
25         slow.next = slow.next.next;
26         return start.next;
27     }
28 }
View Code

 21. Merge Two Sorted Lists

技术分享
 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
11         if (l1 == null) {
12             return l2;
13         }
14         if (l2 == null) {
15             return l1;
16         }
17         ListNode newHead = null; //采用递归调用的思想
18         if (l1.val < l2.val) {
19             newHead = l1;
20             newHead.next = mergeTwoLists(l1.next, l2);
21         } else {
22             newHead = l2;
23             newHead.next = mergeTwoLists(l1, l2.next);
24         }
25         return newHead;
26     }
27 }
View Code

 

LeetCode--链表