leetcode-61-Rotate List
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL Explanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right: 0->1->2->NULL rotate 4 steps to the right: 2->0->1->NULL
解决思路:先用一个指针找到链表的长度i,然后找到反转后的尾节点i-n%i
class Solution {
public ListNode rotateRight(ListNode head, int n) {
if (head==null||head.next==null)
return head;
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode fast=dummy,slow=dummy;
int i;
for (i=0;fast.next!=null;i++)//Get the total length
fast=fast.next;
for (int j=i-n%i;j>0;j--) //Get the i-n%i th node
slow=slow.next;
fast.next=dummy.next; //Do the rotation
dummy.next=slow.next;
slow.next=null;
return dummy.next;
}
}
LeetCode-21-链表-合并两个有序链表
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
方案一:归并中的merge方法
/**
* 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 temp = new ListNode(0);
//定义三个链表的移动指针
ListNode current1=l1;
ListNode current2=l2;
ListNode current3=temp;
int t=0;
while(current1 !=null && current2 !=null){
if(current1.val < current2.val){
current3.next=current1;
current3 = current3.next;
current1=current1.next;
}else{
current3.next=current2;
current3 = current3.next;
current2=current2.next;
}
}
//l2排完,l1未排完
while(current1 !=null){
current3.next=current1;
current3 = current3.next;
current1=current1.next;
}
while(current2 !=null){
current3.next=current2;
current3 = current3.next;
current2=current2.next;
}
return temp.next;
}
}
方案二:递归
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
ListNode mergeNode;
if(l1.val<l2.val){
mergeNode = l1;
mergeNode.next = mergeTwoLists(l1.next,l2);
}else{
mergeNode = l2;
mergeNode.next = mergeTwoLists(l1,l2.next);
}
return mergeNode;
}