//獲取單鏈表結點的個數
public
static
intgetlength
(heronode head)
//定義長度
int length =0;
heronode cur = head.next;
while
(cur != null)
return length;
}
//查詢單鏈表倒數第k個結點
//1.獲取單鏈表長度length
//2.遍歷length-k次即可
public
static heronode findlastindexnode
(heronode head,
int index)
int length =
getlength
(head);if
(index <
0|| index > length)
heronode cur = head.next;
for(
int i =
0; i < length-index; i++
)return cur;
}
//單鏈表的反轉
public
void
reverselist
(heronode head)
//工作指標
heronode cur = head.next;
//工作指標的下乙個
heronode next = null;
heronode reversehead =
newheronode(0
,"",""
);while
(cur != null)
//將head的next指向reversehead的next,實現反轉
head.next = reversehead.next;
}
//從尾到頭列印單鏈表
//1.先進後出=>棧
public
void
reverseprint
(heronode head)
stack
stack =
newstack
<
>()
; heronode cur = head.next;
while
(cur != null)
//棧內大於0
while
(stack.
size()
>0)
}
5.合併兩個有序單鏈表
//合併兩個有序的單鏈表
//1.判斷兩個單鏈表哪個小,小的加入
//2.新增兩個單鏈表最後剩下的
public
static heronode mergelinkedlist
(heronode head1,heronode head2)
if(head2.next == null)
//兩個鍊錶的工作指標
heronode cur1 = head1.next;
heronode next1 = null;
heronode cur2 = head2.next;
heronode next2 = null;
//當鍊表1和2都不到尾部時
while
(cur1 != null && cur2 != null)
else
}//新增剩餘的鍊錶
while
(cur1 != null)
while
(cur2 != null)
return newhead;
}
鏈表面試題
不改變鍊錶結構,從尾到頭列印單鏈表 遞迴實現 void printlistrevers recursively plist phead printf d phead data 當鍊表非常長的時候,遞迴實現的會導致函式呼叫層級很深,可能導致呼叫棧溢位。用棧不會出現此類情況,顯然用棧實現 的魯棒性會好一...
鏈表面試題
從尾到頭列印單鏈表 棧 遞迴 從尾到頭列印鍊錶 includevoid printtailtohead listnode head while s.empty 空間複雜度o n void printtailtoheadr listnode head cout data 刪除乙個無頭單鏈表的非尾結點 ...
鏈表面試題
typedef int datatype typedef struct node node,pnode,plist void initlist plist pplist void display const plist plist void pushback plist pplist,datatyp...