- 单链表反转(头插法)
public Node reverseList() {
Node cur = this.head;
Node prev = null;
while (cur != null) {
Node curNext = cur.next;
cur.next = prev;
prev = cur;
cur = curNext;
}
return prev;
}
- 输入一个链表,输出该链表中倒数第k个节点
思路:
(1)定义fast,slow两个节点
(2)先让fast走k-1步
(3)两个引用同步前进
(4)直到fast.next == null;停止,此时slow所指向的位置就是所求结果
public ListNode FindKthToTail(ListNode head,int k){
if(head == null || k <= 0) {
return null;
}
if(hesd == null || k <= 0){
ListNode fast = head;
ListNode slow = head;
while( k-1 != 0){
if(fast.next != null){
fast = fast.next;
k--;
}else{
return null;
}
}
while(fast.next != null){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
- 将两个有序链表合并为新的有序链表并返回(新链表是通过拼接给定的两个链表的所有节点组成的)
思路:
(1)将较长的那个链表向较短的链表中插入
(2)先取较短的两个链表前两个val
(3)将较长链表中两个val之间的值全部插入
(4)将两个val同时后移
(5)直到curNext.next=null
(6)判断较长链表是否取完
(7)若没有取完则将剩下的全部插入短链表尾端
class Solution {
public ListNode mergeTwoLists(ListNode headA, ListNode headB) {
ListNode newHead = new ListNode(-1);
ListNode tmp = newHead;
while(headA != null && headB != null) {
if(headA.val > headB.val) {
tmp.next = headB;
headB = headB.next;
}else{
tmp.next = headA;
headA = headA.next;
}
tmp = tmp.next;
}
if(headA != null) {
tmp.next = headA;
}
if(headB != null) {
tmp.next = headB;
}
return newHead.next;
}
}
- 编写代码,以给定值x为基准将链表分割为两个部分,所有小于x的结点排在大于或等于x的结点之前
思路:
(1)如果pHead为空直接返回null
(2)定义一个cur从头部开始遍历,发现小于x的值归为一类,大于x的值归为一类
(3)将两类串起来
public class Partition {
public ListNode partition(ListNode pHead, int x) {
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(as != null) {
ae.next = null;
}
return bs;
}
}
- 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead == null) return null;
ListNode newHead = new ListNode(-1);
ListNode tmp = newHead;
ListNode cur = pHead;
while(cur != null) {
if(cur.next != null && cur.val == cur.next.val) {
while(cur.next != null && cur.val == cur.next.val) {
cur = cur.next;
}
cur = cur.next;
}else{
tmp.next = cur;
cur = cur.next;
tmp = tmp.next;
}
}
tmp.next = null;
return newHead.next;
}
}