1.链表的分割
链接:链表分割_牛客题霸_牛客网 (nowcoder.com)https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70?tpId=8&&tqId=11004&rp=2&ru=/activity/oj&qru=/ta/cracking-the-coding-interview/question-ranking
public class Partition {
public ListNode partition(ListNode pHead, int x) {
ListNode cur = pHead;
ListNode bs = null;
ListNode be = null;
ListNode as = null;
ListNode ae = null
if(pHead == null) {
return null;
}
while (cur != null) { //使用cur遍历所有节点
if(cur.val < x) {
if(bs == null) {
bs = cur;
be = cur;
}else {
be.next = cur;
be = be.next;
}
}else {
// cur.val >= x
if(as == null) {
as = cur;
ae = cur;
}else {
ae.next = cur;
ae = ae.next;
}
}
cur = cur.next;
}
if(bs == null) {
return as;
}
be.next = as;
if(as != null) { //尾节点很可能不是空,所以要再次规定尾结点
ae.next = null;
}
return bs;
}文章来源:https://www.toymoban.com/news/detail-826494.html
}文章来源地址https://www.toymoban.com/news/detail-826494.html
2.链表的回文结构
链接:
链表的回文结构_牛客题霸_牛客网 (nowcoder.com)https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa?tpId=49&&tqId=29370&rp=1&ru=/activity/oj&qru=/ta/2016test/question-ranking//快慢指针求解
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class PalindromeList {
public boolean chkPalindrome(ListNode A) {
ListNode cur = null;
ListNode slow = A;
ListNode fast = A.next;
//找中间节点
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next;
}
ListNode Middle = slow;
//翻转中心节点之后的链表值
while(cur != null) {
cur = Middle.next;
ListNode curNext = cur.next;
curNext.next = cur;
cur = curNext;
Middle = Middle.next;
}
cur.next = null;
//判断从链表开头,与中心节点之后的数值是否相等
while(slow != null) {
if(A.val == slow.val) {
A = A.next;
slow = slow.next;
}else {
return false;
}
}
return true;
}
}
到了这里,关于链表分割,链表的回文结构等经典例题解析!的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!