接上篇博客还有5道,赶紧点进去练练手吧~
public class Partition {
public ListNode partition(ListNode pHead, int x) {
// write code here
if(pHead == null){
return null;
}
ListNode bs = null;
ListNode be =null;
ListNode as = null;
ListNode ae = null;
ListNode cur = pHead;
while(cur != null){
if(cur.val < x){
if(bs == null){
bs = cur;
be = cur;
}else{
be.next = cur;
be =be.next;
}
}else{
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(ae != null){
ae.next =null;
}
return bs;
}
}
7. 链表的回文结构。OJ链接
public class PalindromeList {
public boolean chkPalindrome(ListNode A) {
// write code here
if(A == null){
return true;
}
if(A.next == null){
return true;
}
ListNode fast = A;
ListNode slow = A;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode cur = slow.next;
while(cur != null){
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
while(A != slow){
if(A.val != slow.val){
return false;
}
if(A.next == slow){
return true;
}
A = A.next;
slow = slow.next;
}
return true;
}
}
8. 输入两个链表,找出它们的第一个公共结点。OJ链接
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null||headB == null){
return null;
}
ListNode pl = headA;//长的链表头结点
ListNode ps = headB;//短的链表头结点
int lenA = 0;
int lenB = 0;
while(pl != null){
lenA++;
pl = pl.next;
}
while(ps != null){
lenB++;
ps = ps.next;
}
pl = headA;
ps = headB;
int len = lenA - lenB;
if(len<0){
pl = headB;
ps = headA;
len = lenB - lenA;
}
while(len != 0){
pl = pl.next;
len--;
}
while(pl != ps){
pl = pl.next;
ps = ps.next;
}
return pl;
}
}
9. 给定一个链表,判断链表中是否有环。 OJ链接
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null){
return false;
}
if(head.next == null){
return false;
}
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;
}
}
10. 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 NULL OJ链接
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null){
return false;
}
if(head.next == null){
return false;
}
ListNode fast = head;
ListNode slow = head;
while(fast!=null&&fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
break;
}
}
if(fast == null || fast.next == null){
return null;
}
fast = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}