刪除鏈表中指定的所有元素
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null){
return null;
}
ListNode prev = head;
ListNode node = head.next;
while(node != null){
if(node.val == val){
prev.next = node.next;
node = prev.next;
}
else{
prev = node;
node = node.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 newHead = null;
ListNode cur = head;
ListNode prev = null;
while(cur != null){
ListNode next = cur.next;
if(next == null){
newHead = cur;
}
cur.next = prev;
prev = cur;
cur = next;
}
return newHead;
}
}
給定一個帶有頭結點 head 的非空單鏈表,返回鏈表的中間結點。
class Solution {
public ListNode middleNode(ListNode head) {
ListNode cur = head;
int steps = size(head)/2;
for (int i = 0; i < steps; i++){
cur = cur.next;
}
return cur;
}
int size(ListNode head){
int size = 0;
for( ; head!=null;head = head.next, size++);
return size;
}
}
輸出該鏈表中倒數第k個結點
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
int len = size(head);
if( k >len || k <= 0 || head == null){
return null;
}
int offset = len - k;
ListNode cur = head;
for(int i = 0; i < offset; i++){
cur = cur.next;
}
return cur;
}
public int size(ListNode head){
int size = 0;
for(ListNode cur = head; cur != null; cur = cur.next){
size++;
}
return size;
}
}
將兩個有序鏈表合併爲一個新的有序鏈表並返回
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode newList = new ListNode(0);
ListNode tail = newList;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
tail.next = new ListNode(l1.val);
l1 = l1.next;
tail = tail.next;
}
else{
tail.next = new ListNode(l2.val);
l2 = l2.next;
tail = tail.next;
}
}
if( l1 != null ){
tail.next = l1;
}
if( l2 != null ){
tail.next = l2;
}
return newList.next;
}
}