class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null){
return null;
}
ListNode cur = head.next;
ListNode prev = head;
while (cur != null) {
if (val == cur.val){
prev.next= cur.next;
cur = cur.next;
}else{
prev = cur;
cur = cur.next;
}
}
if(head.val == val){
head = head.next;
}
return head;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return null;
}
if(head.next == null){
return head;
}
ListNode cur = head.next;
head.next = null;
while(cur!=null){
ListNode curNext = cur.next;
cur.next = head;
head = cur;
cur = curNext;
}
return head;
}
}
3. 给定一个带有头结点 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。OJ链接
class Solution {
public ListNode middleNode(ListNode head) {
if(head.next == null){
return head;
}
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}
4. 输入一个链表,输出该链表中倒数第k个结点。 OJ链接
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(k <= 0||head == null){
return null;
}
ListNode fast = head;
ListNode slow = head;
while(k -1 > 0){
if(fast.next==null){
return null;
}
fast = fast.next;
k--;
}
while (fast.next != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = new ListNode(-1);
ListNode cur = head;
while(list1!=null &&list2!=null){
if(list1.val <= list2.val){
cur.next = list1;
cur = cur.next;
list1 = list1.next;
}else{
cur.next = list2;
cur = cur.next;
list2 = list2.next;
}
}
cur.next = list1 == null ? list2 : list1;
return head.next;
}
}
还有哦~ 希望我的图解能帮助各位理解链表的问题 下篇博客