码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--链表

时间:2017-05-24 23:53:21      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:lis   递归调用   gif   head   node   ide   div   public   style   

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--链表

标签:lis   递归调用   gif   head   node   ide   div   public   style   

原文地址:http://www.cnblogs.com/muziyueyueniao/p/6901399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!