链表部分
NC78 反转链表
定义前驱结点prev、next 、
在这里插入代码片
public class Solution {
public ListNode ReverseList(ListNode head){
if(head==null){
return null;
}
ListNode prev = null;
ListNode next = head;
while(head!=null){
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}
NC4 判断链表中是否有环
(双指针问题)链表有环,快慢指针会相遇;
在这里插入代码片
public class Solution {
public boolean hasCycle(ListNode head){
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast==slow){
return true;
}
}
return false;
}
}
NC33 合并两个排序的链表
在这里插入代码片
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode node = new ListNode(0);
ListNode prev = node;
node.next = null;
while(list1 !=null&& list2!=null){
if(list1.val < list2.val){
node.next = list1;
node = list1;
list1 = list1.next;
}else{
node.next = list2;
node = list2;
list2 = list2.next;
}
}
if(list1!=null)
node.next = list1;
if(list2!=null)
node.next = list2;
return prev.next;
}
}