19.删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
别忘了在最初的时候保存一下链表的头结点!!!在下面head就一点一点的变成head.next了!!!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode head1 = new ListNode(0);
ListNode jieguo = head1;
ListNode tou = head ;
//int i;
int number = 0;
int i;
for(i=0;;i++)
{
if(head == null)
{
break;
}
head= head.next;
}
// System.out.printf("%d\n",i-n+1);
head = tou;
for(number=1;number<=(i-n);number++)
{
head1.next = new ListNode(head.val);
// System.out.printf("%d\n",head1.next.val);
head1 = head1.next;
head = head.next;
}
head = head.next;
while(head!=null)
{
head1.next = new ListNode(head.val);
//System.out.printf("%d\n",head1.next.val);
head1 = head1.next;
head = head.next;
}
return jieguo.next;
}
}
21. 合并两个有序链表
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode ending = head;
int i;
int flag1 = 1;
int flag2 = 1;
while((l1!=null)||(l2!=null))
{
if(l1 == null)
{
flag1 = 0;
}
if(l2 == null)
{
flag2 =0;
}
if(flag1 == 0)
{
head.next = new ListNode(l2.val);
head = head.next;
l2 = l2.next;
}
else
{
if(flag2 ==0)
{
head.next = new ListNode(l1.val);
head = head.next;
l1 = l1.next;
}
else
{
if(l1.val<=l2.val)
{
head.next = new ListNode(l1.val);
head = head.next;
l1 = l1.next;
}
else
{
head.next = new ListNode(l2.val);
head = head.next;
l2 = l2.next;
}
}
}
}
return ending.next;
}
}
执行用时: 9 ms, 在Merge Two Sorted Lists的Java提交中击败了92.36% 的用户
内存消耗: 25.4 MB, 在Merge Two Sorted Lists的Java提交中击败了77.32% 的用户
第一次超过了90%+的用户!!!纪念一下。
23. 合并K个排序链表
忘了在第一次循环之后把min弄到初始值了。。。找了很久的错误。。。每次进行完一个判断之后别忘了把需要初始化的东西初始化!!!
int number = lists.length;可以用于计算二维数组中有多少个一维数组。
二维数组是数组的数组!!!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode head = new ListNode(0);
ListNode tou = head;
int number = lists.length;
int i;
int j;
int record = 0;
int min = 100000;
int recordi = 0;
// System.out.printf("%d\n",number);
for(j=0;;j++)
{
for(i = 0;i < number;i ++)
{
if(lists[i] == null)
{
record = record + 1;
}
else
{
if(lists[i].val<=min)
{
min = lists[i].val;
recordi = i;
}
}
}
min = 100000;
if(record == number)
{
break;
}
record = 0;
head.next = new ListNode(lists[recordi].val);
head = head.next;
lists[recordi] = lists[recordi].next;
}
return tou.next;
}
}