链表习题一定要画图!
例一 :链接的中间节点
题目详述:
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
public ListNode middleNode(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
例二 :输入一个链表,输出该链表中倒数第k个结点。
public class Solution {
public ListNode FindKthToTail(ListNode head, int k) {
//输入一个链表,输出该链表中倒数第k个结点
ListNode pre = head;
ListNode p = head;
//记录k值
int a = k;
//记录节点的个数
int count=0;
//p指针先跑,并且记录节点数,当p指针跑了k-1个节点后,pre指针开始跑,
//当p指针跑到最后时,pre所指指针就是倒数第k个节点
while(p!=null){
p=p.next;
count++;
if(k<1){
pre=pre.next;
}
k--;
}
//如果节点个数小于所求的倒数第k个节点,则返回空
if(count<a) {
return null;
}
return pre;
}
}
例三 :合并两个有序链表
题目详述:将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode node = new ListNode(-1);
ListNode cur = node;
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
cur.next = l1;
cur = cur.next;
l1 = l1.next;
}else {
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
if(l1 == null) {
cur.next = l2;
}else {
cur.next = l1;
}
return node.next;
}
}
例四 :排序
题目详述:
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前。
PS:分割以后保持原来的数据顺序不变
public class Partition {
public ListNode partition(ListNode pHead, int x) {
ListNode node = new ListNode(-1);
ListNode node1 = new ListNode(-1);
if (pHead == null || pHead.next == null) {
return pHead;
}
//设置两个链表
//小于x的结点链表:head 为头结点,tail 为尾结点
ListNode head = node;
ListNode tail = node;
//大于或等于x的结点链表:h 为头结点,t 为尾结点
ListNode h = node1;
ListNode t = node1;
ListNode cur = pHead;
while (cur != null) {
if(cur.val < x) {
tail.next = cur;
tail = tail.next;
}else {
t.next = cur;
t = t.next;
}
cur = cur.next;
}
tail.next = h.next;
t.next = null;
return head.next;
}
}
例五 :删除重复节点
题目详述:
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
ListNode node = new ListNode(-1);
ListNode tmp = node;
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;
tmp = tmp.next;
cur = cur.next;
}
}
tmp.next = null;
return node.next;
}
}