1. 程式人生 > >線性表---單鏈表(逆置)

線性表---單鏈表(逆置)

假設需要逆序的單鏈表為:
這裡寫圖片描述

則逆置以後的連結串列為:
這裡寫圖片描述

程式碼如下:

#include<iostream>
#include<malloc.h>
using namespace std;

typedef struct node
{
    int num;
    struct node *next;
}Node;

Node * CreateList(int a[], int n)
{
    Node *head, *p, *q;

    head = (Node*)malloc(sizeof(Node));
    head->next = NULL;

    p = head;
    for
(int i=0; i<n; i++) { q = (Node*)malloc(sizeof(Node)); q->num = a[i];//陣列元素給連結串列賦值!!! p->next = q; p = q; } p->next = NULL;//將最後一個結點的指標域清空 return head;//返回這個連結串列的首地址 } void PrintList(Node *head) { Node *p; p = head->next;//從第一個元素(頭元素)開始,依次往後
while(p) { cout<<p->num<<" "; p = p->next; } cout<<endl; } /*-------------------------------------------------------------- ////////////單鏈表逆序///////////// ----------------------------------------------------------------*/ Node *ListReverse(Node *head) { Node *current, *pnext, *prev; if
(head == NULL || head->next == NULL) return head; current = head->next;//結點current指向首元結點 pnext = current->next;//pnext用來儲存當前節點的下一個節點 //current->next一旦將值賦給pnext之後,就可將其置空.它是倒序後的尾結點,所以為空。 current->next = NULL; while(pnext) { //prev用於儲存pnext->next,因為這個值將是新連結串列current的前驅 prev = pnext->next;//讓pnext當前的後繼作為逆置後的前驅 pnext->next = current;//將current和pnext進行逆置 /*分別更新curren和pnext。 往後遍歷,使得前面兩步操作往後進行. 我們的目的是將current這個儲存當前結點的元素移向後一個結點, 同時把pnext也向後一位,其實就是要把pnext的值賦給current, 還有prev的值賦給pnext*/ current = pnext;//更新current pnext = prev;//更新pnext } head->next = current;//將連結串列頭節點指向currnt return head; } int main() { int a[]={1, 2, 3, 4}; Node *head = CreateList(a, 4); PrintList(head); ListReverse(head); PrintList(head); return 0; }

結果:

1 2 3 4
4 3 2 1

Process returned 0 (0x0)   execution time : 0.224 s
Press any key to continue.