輸出鏈表倒數第n個節點資料

來源:互聯網
上載者:User

考慮特殊情況:
1. 鏈表頭指標為空白,n小於等於0是錯誤輸入

2. 鏈表實際節點數小於n


因此代碼:


#include <stdio.h>#include <stdlib.h>typedef struct node{        int a;        struct node *link;    }mynode;int creat_tail(mynode *head,int n){        mynode *node = head,*new;        int x;        if(n <= 0){            printf("error: n <= 0");            return 0;        }        for(;n > 0;n--){          new = (mynode*)malloc(sizeof(mynode));             printf("enter a number:\n");             scanf("%d",&x);            new->a = x;            new->link = NULL;            node->link = new;  //隨動指標          node = node->link;        }    }mynode* search(mynode *head,int n){    mynode *front = head,*behind = head;        if(head == NULL || n <= 0)    return NULL;    while(front->link != NULL && n > 0){        front = front->link;        n--;    }    if(n > 0)    return NULL;    while(front != NULL){        front = front->link;        behind = behind->link;    }    return behind;}//正向列印  void print_nodes1(mynode *head){        int n = 1;        mynode *node;      if(head != NULL){          node = head->link;            while(node != NULL){                printf("num:%d\t a=%d\n",n,node->a);                node = node->link;                n++;            }      }      }  void main(){    mynode *head,*value;        creat_tail(head,1);    print_nodes1(head);    value = search(head,1);    printf("%d\n",value->a);    getch();}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.