public static ListNode removeNthFromEnd(ListNode head, int n) {
int length=0;
ListNode temp=head;
ListNode pre=head;
while (temp!=null){
length++;
temp=temp.next;
}
int aim=length-n;
if (aim==0){
return head.next;
}
for (int i=0;i<aim-1;i++){
pre=pre.next;
}
pre.next=pre.next.next;
return head;
}
//反转链表
public static ListNode reverseList1(ListNode head) {
ListNode newHead=null;
while (head !=null){
ListNode temp=head.next;
head.next=newHead;
newHead=head;
head=temp;
}
return newHead;
}
public static ListNode reverseList2(ListNode head) {
Stack<ListNode> stack =new Stack<>();
while (head !=null){
stack.push(head);
head=head.next;
}
if (stack.isEmpty()){
return null;
}
ListNode node=stack.pop();
ListNode dummy=node;
while (!stack.isEmpty()){
ListNode temp=stack.pop();
node.next=temp;
node=node.next;
}
node.next=null;
return dummy;
}
//
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null){
return list2;
}
if (list2 == null){
return list1;
}
ListNode newNode=new ListNode(0);
ListNode res=newNode;
while (list1!=null&&list2!=null){
if (list1.val<=list2.val){
newNode.next=list1;
list1=list1.next;
}else {
newNode.next=list2;
list2=list2.next;
}
newNode=newNode.next;
}
newNode.next=list1==null?list2:list1;
return res.next;
}
//回文链表
public static boolean isPalindrome(ListNode head) {
ListNode temp = head;
Stack<Integer> stack = new Stack();
//把链表节点的值存放到栈中
while (temp != null) {
stack.push(temp.val);
temp = temp.next;
}
//然后再出栈
while (head != null) {
if (head.val != stack.pop()) {
return false;
}
head = head.next;
}
return true;
}
//环形链表
public boolean hasCycle1(ListNode head) {
if (head ==null){
return false;
}
ListNode slow=head;
ListNode fast=head;
while (fast!=null&&slow!=null){
slow=slow.next;
fast=fast.next.next;
if (slow==fast){
return true;
}
}
return false;
}
public boolean hasCycle2(ListNode head) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
//如果重复出现说明有环
if (set.contains(head)){
return true;
}
//否则就把当前节点加入到集合中
set.add(head);
head = head.next;
}
return false;
}
算法学习三链表
最新推荐文章于 2024-05-04 09:38:05 发布