1. 程式人生 > >連結串列翻轉【比如連結串列1→2→3→4→5→6,k=2, 翻轉後2→1→4→3→6→】

連結串列翻轉【比如連結串列1→2→3→4→5→6,k=2, 翻轉後2→1→4→3→6→】

2.【附加題】–1、連結串列翻轉,給出一個連結串列和一個數k,比如連結串列1→2→3→4→5→6,k=2,
翻轉後2→1→4→3→6→5,若k=3,翻轉後3→2→1→6→5→4,若k=4,翻轉後4→3→2→1→5→6,
用程式實現Node* RotateList(Node* list, size_t k). 提示:這個題是連結串列逆置的升級變型。

#include<iostream>
using namespace std;
typedef struct ListNode
{
    int data;
    ListNode* next;
    ListNode(const int&
x) :data(x) ,next(NULL) {} }Node; Node* fun1(Node* PHead)//連結串列逆置 { //1.連結串列為空,直接返回或者連結串列只有一個結點,直接返回 if (PHead==NULL||PHead->next==NULL) { return PHead; } //連結串列有多個結點 Node* cur=PHead; Node* next=NULL; Node* PNewHead=NULL; while (cur) { next=
cur->next; cur->next=PNewHead; PNewHead=cur; cur=next; } return PNewHead; } Node* fun2(Node* PHead)//獲得連結串列最後一個結點 { //1.連結串列為空或者只有一個結點 if (PHead==NULL||PHead->next==NULL) { return PHead; } //2.連結串列有多個結點 Node* cur=PHead; while (cur->
next) { cur=cur->next; } return cur; } Node* fun3(Node* PHead,int k)//連結串列翻轉 { //1.如果連結串列為空或者只有一個結點 if (PHead==NULL||PHead->next==NULL) { return PHead; } //2.連結串列有多個結點 Node* cur=PHead;//遍歷每段小連結串列 Node* PNewHead=NULL;//記錄每段小區間的頭結點 Node* PLastNode=NULL;//記錄每段小區間的尾結點 Node* PNextNode=NULL;//記錄下一個區間的的頭結點 PHead=NULL;//記錄翻轉以後的連結串列的頭0 while (cur) { int pos=0; PNewHead=cur;//要翻轉的小連結串列的頭結點 //cur走到小連結串列的尾端來判斷該小連結串列的節點個數是否小於3 while (cur&&pos<k-1) { cur=cur->next; pos++; } //如果cur為空,說明該段區間不夠k個結點,不用翻轉 if (cur) { PNextNode=cur->next;//記錄下一個小連結串列的頭結點 cur->next=NULL;//將該段小連結串列與總連結串列分離 PNewHead=fun1(PNewHead);//將該段小連結串列逆置 if (PLastNode==NULL)//如果是第一段小區間,則要記住連結串列的頭,這就是連結串列翻轉以後的頭結點 { PHead=PNewHead; } //1.小連結串列逆置完以後要連線到總連結串列中:除了第一個小連結串列外,都需要分兩步1.連結到前面連結串列2.連線到後面連結串列 else//1.1除了第一個小連結串列之外,後面的連結串列都要連線到前面已經逆置好的連結串列的尾部; { PLastNode->next=PNewHead; } //1.2將逆置以後的小連結串列連結到後面的連結串列 PLastNode=fun2(PNewHead);//求逆置以後的小連結串列的尾結點 PLastNode->next=PNextNode;//將逆置以後的小連結串列連線到總連結串列上 cur=PNextNode;//更新cur,開始遍歷下一個連結串列 } } return PHead; } void Printf(Node* PHead) { if (PHead==NULL) { return ; } else { Node* cur=PHead; while (cur) { cout<<cur->data<<" "; cur=cur->next; } } } int main() { Node* node1=new Node(1); Node* node2=new Node(2); Node* node3=new Node(3); Node* node4=new Node(4); Node* node5=new Node(5); Node* node6=new Node(6); node1->next=node2; node2->next=node3; node3->next=node4; node4->next=node5; node5->next=node6; Printf(node1); cout<<endl; //Node* Phead1=fun3(node1,2); //Printf(Phead1); //cout<<endl; //Node* Phead2=fun3(node1,3); //Printf(Phead2); //cout<<endl; Node* Phead3=fun3(node1,4); Printf(Phead3);