定义
class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val=val;
this.next=null;
}
}
1.1 2根指针思路, dummy + cur;
1.2 cur提前存储next元素,解决了翻转时linkedlist断裂问题;
1.3 dummy用于保存遍历后的头部;
public static ListNode reverseListNonRecursive(ListNode head)
{
// 新建一个dummy
ListNode dummy = new ListNode(0);
// dummy指向头部,即dummy再head前面
dummy.next = head;
// 边界条件;如果head或者head.next是null,直接返回head;即,没有元素或者只有一个元素;
if (head == null || head.next == null)
return head;
// 从第2个node开始遍历;原因:head.next下一步将需要设置为null
ListNode curr = head.next;
//head.next置为null
head.next = null;
//从2号node开始遍历,实施如下动作:1 curr.next前指; 2 dummy.nexe指向curr; 3 curr后移
while (curr != null)
{
//存储curr的next,为curr后移做准备
ListNode tmp = curr.next;
//1 curr.next前指
curr.next = dummy.next;
//dummy.nexe指向curr
dummy.next = curr;
//3 curr后移
curr = tmp;
}
//返回dummy.next;
return dummy.next;
}
递归实现方式思路图(带入例子1->2->3)
public static ListNode reverseListRecursive(ListNode head)
{
if ( head== null || head.next == null) //边界条件
return head;
ListNode secondtNode = head.next;//保存状态为nextNode
head.next = null;
ListNode reverseRest = reverseListRecursive( secondtNode);//通过递归翻转剩余部分链表,返回翻转后的头部为reverseRest
secondtNode.next = head; //2号node前指1号node
return reverseRest;
}
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
if(l1==null||l2==null)
return l1==null?l2:l1;
ListNode dummy = new ListNode(0);
ListNode cur = dummy;//初始化cur=dummy,
//l1,l2任意1个不为null , 使用l1!=null, 而不是l1.next!=null;因为:要走到最后一个元素;
while(l1 != null && l2 != null)
{
if(l1.val <= l2.val)
{
cur.next = l1;//因为cur初始化为dummy.next
l1 = l1.next;
}
else
{
cur.next = l2;
l2 = l2.next;
}
cur=cur.next;
}
//把剩下的list接在l3后面
if(l1!=null)
cur.next = l1;
else if(l2 != null)
cur.next=l2;
//返回
return dummy.next;
}
}
--------------------------------------------------------------------------------------------------------------------
3 环的长度
public Node hasCycle(Node head)
{
if(head == null)
return null;
Node slow=head;
Node fast=head;
while(fast != null && fast.next!=null && fast.next.next!=null)
{
//注意:先增,后比较相等;否则,首次指向head,一定会相等;
slow=slow.next;
fast=fast.next.next;
if(slow==fast)
return slow;
}
return null;
}
//node指的是首次相遇节点
public int GetCycleLength(Node node)
{
if(node=null)//边界条件
return 0;
Node slow = node;
Node fast= node;
length=0;
while(fast!=null&&fast.next.next!=null)
{
slow=slow.next
fast=fast.next.next;
length++;
if(slow==fast)
return length;
}
return length;
}