2013-02-28 32 views
3

可以說我有字符串「燈」,它被傳遞到我的程序中,每個字符都存儲在鏈接列表中的一個節點中。如何在鏈接列表中向後移動?

我需要使用另一個鏈表以相反的順序複製該列表,我該如何做到這一點,我已經相當遠了,但是如何向後移動鏈接列表?

你會看到該行評論我需要放在那裏在鏈表中向後移動。

#include <stdlib.h> 
#include <stdio.h> 

struct NODE { 
    struct NODE *next; 
    char data; 

}; 


int main(int argc, char *argv[]) { 

int i; 

struct NODE *head; 
struct NODE *current; 
struct NODE *head2; 
struct NODE *current2; 
struct NODE *finger; 


for(i = 0; i < argc; i++) 
    printf("arg %d: %s\n", i, argv[i]); 

head = (struct NODE*)malloc(sizeof(struct NODE)); 
    current = head; 


    for (i = 0; i < sizeof(argv[1]) - 1; i++) { 

    current -> data = argv[1][i]; 
    current -> next = (struct node*)malloc(sizeof(struct NODE)); 
    current = current -> next; 
    current -> next = NULL; 

} 


head2 = (struct NODE*)malloc(sizeof(struct NODE)); 
    current2 = head2; 

    while (current != head) { 

     finger = head; 


    while (finger -> next != current) 

     finger = finger -> next; 
     current2 -> data = current -> data; 
     current2 -> next = (struct node*)malloc(sizeof(struct NODE)); 
     current2 = current2 -> next;  
     // move backwards 



    } // ends loop 



} 






return 0; 

} 

回答

2

簡短的版本是與上一個變量擴展你的結構,當你創建一個子分配自到它的父變量,因此你可以在以後,從孩子讀這是移動一個向後父變量 - 然後遞歸到頂端。

5

如何在(單獨)鏈接列表中向後移動?

你不知道。將一個列表翻轉爲另一個列表的技巧是插入目標列表的頭部而不是後部。您需要遵循next指針以常規方式遍歷原始列表,但不是將元素添加到目標列表的末尾,而是創建一個新節點,並用它替換目標的標題。

這裏是一個一步一步說明:

sourceHead -> "A" -> "B" -> "C" -> NULL 
your pointer ^
targetHead -> NULL 

sourceHead -> "A" -> "B" -> "C" -> NULL 
your pointer  ^
targetHead -> "A" -> NULL 

sourceHead -> "A" -> "B" -> "C" -> NULL 
your pointer    ^
targetHead -> "B" -> "A" -> NULL 

sourceHead -> "A" -> "B" -> "C" -> NULL 
your pointer      ^
targetHead -> "C" -> "B" -> "A" -> NULL