最近有空就在LeetCode上刷下题,在工作中虽然很少自已写算法,JDK已经的封装好了,直接拿来就用,但是平常有空刷下题对于理解这些封装的集合API及选用还是挺有帮助的。毕竟不是计算机科班出身的,数据结构与算法平常还是要多补下。
- 删除链表倒数第n个数
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//计算长度
ListNode point = head;
int length = 1;
while (null != point.next) {
point = point.next;
length++;
}
if (n > length)
{
return head;
}
ListNode temp = head;
if (length == n) {
head = temp.next;
temp.next = null;
return head;
}
int i = 1;
while (null != temp.next && i + n < length) {
temp = temp.next;
i++;
}
//此时temp处于倒数n+1个node上
ListNode nthNode = temp.next;
temp.next = nthNode.next;
nthNode.next = null;
return head;
}
}
- 删除链表中相同的元素
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
public ListNode deleteDuplicates(ListNode head) {
//只有一个节点或节点为空
if (null == head || null == head.next) {
return head;
}
ListNode point = head;
ListNode temp = null;
int flag = 0;
while (null != point && null != (temp = point.next)) {
//前N个节点相同的情况
while (null != temp && point.val == temp.val) {
temp = temp.next;
point = point.next;
flag++;
}
if (0 != flag) {
point.next = null;
point = temp;
head = point; //表头重新赋值
flag = 0;
continue;
}
while (null!= temp.next && temp.val == temp.next.val) {
temp = temp.next;
flag++;
}
if (0 != flag) {
point.next = temp.next;
temp.next = null;
flag = 0;
continue; //链表重新组装后需要再次进入循环
}
point = point.next;
}
return head;
}
- Reorder List
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes’ values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
public void reorderList(ListNode head) {
//排除null,节点数为1或2的List
if (null == head || null == head.next || null == head.next.next) {
return;
}
ListNode point = head;
ListNode secondaryEnd = head.next; //倒数第二个节点
while (null != secondaryEnd.next && null != secondaryEnd.next.next) {
secondaryEnd = secondaryEnd.next;
}
ListNode end = secondaryEnd.next; //最后一个节点
if (null != point.next) {
secondaryEnd.next = null;
end.next = point.next;
point.next = end;
point = end.next;
reorderList(point);
}
}
这种解法的平均时间复杂度应该是 O(n2) , 在LeetCode中报超时,暂时还未想到更快的办法。