目錄
1.移除鍊錶元素(刪除鍊錶中等於給定值val的所有節點)
2.反轉乙個鍊錶
3.找出鍊錶的中間結點
4.輸出鍊錶中倒數第k個結點
5.合併兩個有序鍊錶,合併後依然有序
6.找出兩個單鏈表相交的起始結點
輸入:1->2->6->3->4->5->6,val=6輸出:1->2->3->4->5
/**
* definition for singly-linked list.
* public class listnode
* }*/class solution elseelse
}if(head.val == val)
}return head;}}
輸入:1->2->3->4->5->null輸出:5->4->3->2->1->null
/**
* definition for singly-linked list.
* public class listnode
* }*/class solution
if(head.next == null)
listnode pre = head;
listnode cur = pre.next;
head.next = null;
while(cur.next != null)
cur.next = pre;
head = cur;
return head;}}
給定乙個帶有頭結點head的非空單鏈表,返回鍊錶的中間結點。如果有兩個中間結點,則返回第二個中間結點)
輸入:[1,2,3,4,5]輸出:此列表中的結點3(序列化形式:[3,4,5])
/**
* definition for singly-linked list.
* public class listnode
* }*/class solution
int middleindex = length/2;//2
listnode res = head;
while(middleindex != 0)
return res;}}
/*
public class listnode
}*/public class solution
int length = 0;
listnode cur = head;
while(cur != null)
if(k<=0 || k>length)
int position = length-(k-1);
int tmp = 1;
cur = head;
while(tmp != position)
return cur;}}
輸入:1->2->4, 1->3->4輸出:1->1->2->3->4->4
/**
* definition for singly-linked list.
* public class listnode
* }*/class solution else if(l2 == null)else if(l1.val < l2.val)else }}
分析一下,這兩個單鏈表的狀態應該是這樣的:
//a比b短
if(sublen < 0)
//2.長的先走sublen步
for(int i=0; i
//3.開始同時走
while(pl != null && ps != null && pl != ps)
if(pl == ps && pl != null)
return null;}}
單鏈表相關題目
1.獲取鍊錶中的有效節點數 2.方法 獲取到單鏈表的節點的個數 如果是帶頭結點的鍊錶,需求不統計頭節點 3.public static intgetlength hero head 7.int length 0 8.定義乙個輔助的變數,這裡我們沒有統計頭節點 9.hero temp head.get...
單鏈表相關演算法
include include using namespace std typedef int elemtype typedef struct node nodetype nodetype create s next null return head void dis nodetype head w...
單鏈表相關操作
這是自己寫的最長的一次 了 在機房敲了一天。以前一直用list來水鍊錶的題 這次終於體會到痛苦了 include include include include include include using namespace std typedef struct node 單鏈表 s,list vo...