leetcode演算法題 重排鍊錶

2021-10-05 22:45:50 字數 1547 閱讀 1743

1、map

void

reorderlist

(listnode* head)

for(

int i=

0,j=n-

1;i,j--

)}

2、遞迴★★

void

reorderlist

(listnode* head)

int len=0;

listnode *p=head;

while

(p!=

null

)reorderlisthelper

(head,len);}

listnode *

reorderlisthelper

(listnode *head,

int len)

if(len==2)

listnode *tail=

reorderlisthelper

(head-

>next,len-2)

;//相當於快慢指標,當len==1時,總數為奇數,head正好走到中點;當len==2時,總數為偶數,head走到中間左邊的節點。

listnode *subhead=head-

>next;

//子鍊錶的頭結點

head-

>next=tail;

listnode *outtail=tail-

>next;

//上一層head對應的tail

3、雙鏈表

示例:

1

->2-

>3-

>4-

>5-

>

6第一步,將鍊錶平均分成兩半1-

>2-

>34

->5-

>

6

第二步,將第二個鍊錶逆序1-

>2-

>36

->5-

>

4

第三步,依次連線兩個鍊錶1-

>6-

>2-

>5-

>3-

>

4

**:

void

reorderlist

(listnode* head)

q=reverse

(p->next)

;//分隔鍊錶,並且將後半部分倒序

p->next=

null

; p=head;

while

(q!=

null)}

listnode*

reverse

(listnode* head)

leetcode 重排鍊錶

1.使用快慢指標,將鍊錶分成前後兩個部分 listnode fast head listnode slow head while fast null fast.next null listnode mid slow solw指向中間節點 listnode first head listnode se...

重排鍊錶(LeetCode)

題目鏈結 給定乙個單鏈表 l l0 l1 ln 1 ln 將其重新排列後變為 l0 ln l1 ln 1 l2 ln 2 你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。示例 1 給定鍊錶 1 2 3 4,重新排列為 1 4 2 3.示例 2 給定鍊錶 1 2 3 4 5,重新排列為 ...

演算法 重排鍊錶

definition for singly linked list.public class listnode listnode int val listnode int val,listnode next class solution 通過快慢指標方法找到鍊錶中間節點,如果是偶數節點個數,則是前半...