比较简单的几道题,不做详细的解释,只为之后可以回头看看自己之前的代码!!
虽然几道题都比较简单,但感觉自己写得不好,希望博文如果被哪位大神看到,可以留言下写下你的做法!
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n =
4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
AC代码:
public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if (head == null) return null; if (m == n) return head; ListNode pHead = new ListNode(0); pHead.next = head; ListNode preMNode = getListNode(pHead, m-1); ListNode MNode = getListNode(pHead, m); ListNode preNode = preMNode; int len = n-m; for (int i=0; i<=len; ++i){ ListNode MNodeNext = MNode.next; MNode.next = preNode; preNode = MNode; MNode = MNodeNext; } preMNode.next.next = MNode; preMNode.next = preNode; return pHead.next; } public ListNode getListNode(ListNode startNode, int index){ for (int i=0; i<index; ++i){ startNode = startNode.next; } return startNode; } }
Given a binary tree, return the inorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.
public class Solution { public ArrayList<Integer> inorderTraversal(TreeNode root) { ArrayList<Integer> arrays = new ArrayList<Integer>(); if (root == null) return arrays; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while (!stack.empty()){ TreeNode topNode = stack.peek(); if (topNode.left != null){ stack.push(topNode.left); topNode.left = null; continue; } stack.pop(); arrays.add(topNode.val); if (topNode.right != null){ stack.push(topNode.right); } } return arrays; } }
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
AC代码:
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode list = new ListNode(0); ListNode newlist = list; if (l1 == null){ list = l2; return list; } if (l2 == null){ list = l1; return list; } while (l1 != null && l2 != null){ if (l1.val < l2.val){ list.next = l1; list = list.next; l1 = l1.next; }else{ list.next = l2; list = list.next; l2 = l2.next; } } if (l1 != null){ list.next = l1; } if (l2 != null){ list.next = l2; } return newlist.next; } }
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
AC代码:
public class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) return true; if (p == null) return false; if (q == null) return false; if (p.val != q.val) return false; return isSameTree(p.left,q.left) && isSameTree(p.right,q.right); } }
leetCode解题报告之几道基础题,布布扣,bubuko.com
原文:http://blog.csdn.net/ljphhj/article/details/21865025