1.快慢指针
public ListNode endOfFirstHalf(ListNode head){
ListNode slow=head;
ListNode fast=head;
while(fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
2.链表翻转
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode curr=head;
ListNode next;
while(curr!=null){
next=curr.next;
curr.next=pre;
pre=curr;
curr=next;
}
return pre;
}
public ListNode reverseList(ListNode head) {
Stack<ListNode> stack=new Stack<>();
ListNode start=new ListNode(0,new ListNode(0));
ListNode temp=start;
while(head!=null){
stack.push(head);
head=head.next;
}
while(!stack.isEmpty()){
temp.next=stack.pop();
temp=temp.next;
}
temp.next=null;
return start.next;
}
}
3.链表合并
public ListNode merge(ListNode h1,ListNode h2){
ListNode dummy=new ListNode(0);
ListNode temp=dummy,temp1=h1,temp2=h2;
while(temp1!=null&&temp2!=null){
if (temp1.val<=temp2.val) {
temp.next=temp1;
temp1=temp1.next;
}else{
temp.next=temp2;
temp2=temp2.next;
}
temp=temp.next;
}
if (temp1!=null) {
temp.next=temp1;
}
if (temp2!=null) {
temp.next=temp2;
}
return dummy.next;
}