Xoá phần tử thứ N trong Danh sách liên kết con trỏ bằng C

Đây là chương trình xoá phần tử thứ n trong danh sách liên kết, chương trình được viết bằng C, các bạn cùng tham khảo.

#include
#include
#include
#include

typedef struct tagsl {
int key;
struct tagsl *next;
} SL;

SL *first, *last;

void initialize()
{
first = last = NULL;
}

void cleanup()
{
SL *f;

while (first != NULL)
{
f = first;
first = first->next;
free(f);
}
first = last = NULL;
}

void insert(int key)
{
SL *s;

s = (SL *)malloc(sizeof(SL));
s->key = key;
s->next = NULL;
if (first == NULL)
first = last = s;
else
{
last->next = s;
last = last->next;
}
}

void inds()
{
SL *f;
printf(“\nDanh sach : “);
f = first;
while (f != NULL)
{
printf(“%3d”, f->key);
f = f->next;
}
}

int xoa_n(int n)
{
SL *f, *a;
int i = 0;
a = NULL;
f = first;
while (inext;
}
if (f == NULL)
return 0;
else
{
if (a == NULL)
{
first = f->next;
free(f);
}
else if (f->next == NULL)
{
last = a;
last->next = NULL;
free(f);
}
else
{
a->next = f->next;
free(f);
}
return 1;
}
}

void main()
{
int i, n;
initialize();
randomize();
for (i=0; i<20; i++)
insert(random(20));
inds();
do {
printf(“\nXoa phan tu thu (<0 de thoat) : “); scanf(“%d”, &n); if (n>-1)
{
if (xoa_n(n))
inds();
else
printf(“Danh sach co it hon %d phan tu”, n+1);
}
} while (n > -1);
cleanup();
}

Cùng chạy chương trình và xem kết quả thế nào nhé.

Ví dụ về danh sách liên kết, sử dụng con trỏ trong c

Đây là ví dụ về danh sách liên kết sử dụng con trỏ trong c

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <iostream.h>
#include <dos.h>
#define false 0
#define true 1
struct nhansu {char ten[20];int tuoi;nhansu* next;};
int snv;nhansu *phead,*pcurrent;
void khoitao();
void nhap();
void xem();
void sapxep();
void sapxep2();
//=================================
void main()
{const int F1=59,F2=60,F3=61,F4=62,F10=68;
char chon;
while(true)
  {clrscr();
   printf(“\nF1. Khoi tao”);
   printf(“\nF2. Nhap”);
   printf(“\nF3. Xem”);
   printf(“\nF4. Sap xep”);
   printf(“\nF10.Ket thuc”);
   printf(“\n    Nhan phim F1 – F10 de chon”);
   chon=getch();
   if(chon==0) chon=getch();
   if(chon==F10) break;
   switch(chon)
    {case F1: khoitao();break;
     case F2: nhap();break;
     case F3: xem();break;
     case F4: sapxep2();break;
    }
   gotoxy(50,24);
   printf(“Nhan phim bat ky de tiep tuc”);
   getch();
  }
}
//========================================
void khoitao()
{phead=NULL;
  snv=0;pcurrent=NULL;
};
//========================================
void nhap()
{int i,mm;
  nhansu *p1,*p, *tmp;
  p=p1=phead;
  while(p!=NULL)
   {p1=p;
    p=p->next;
   }
  cout<<endl<<“Nhap bao nhieu nguoi?”;cin>>mm;
  for(i=0;i<mm;i++)
   {tmp=new nhansu;tmp->next=NULL;
    cout<<endl<<“Nhap nhan vien thu “<<snv+i+1<<“: “;
    cout<<endl<<“Ten: “;gets(tmp->ten);
    cout<<“Tuoi: “;cin>>tmp->tuoi;
    if(p1==NULL)
     {p1=phead=tmp;}
      else
      {p1->next=tmp;p1=tmp;}

   }
  snv+=mm;
  pcurrent=p1;
}
//========================================
void xem()
{int i;
  cout<<endl<<“Danh sach nhan vien:”;
  cout<<endl<<“Ten      tuoi”;
  nhansu *p=phead;
  while(p!=NULL)
   {cout<<endl<<p->ten<<”        “<<p->tuoi;
    p=p->next;
   }
}
//========================================
void sapxep()
{if(snv<2) return;
  nhansu *p,*p1,*p2,*ptmp,tmp;int mtuoi;
  p=p1=p2=phead;
  //pt truoc p,p1t truoc p1
  while(p1!=NULL)
   {p=p1;
    p2=p1->next;
    while(p2!=NULL)
     {if(p2->tuoi<p->tuoi) p=p2;
      p2=p2->next;
     }
    if(p!=p1)
     {tmp=*p1;ptmp=p1->next;
      *p1=*p;p1->next=ptmp;
      ptmp=p->next;*p=tmp;
      p->next=ptmp;
     }
    p1=p1->next;
   }
}
//========================================
void sapxep2()
{if(snv<2) return;
  nhansu *p,*pt,*p1,*p1t,*p2,*p2t,*ptmp,tmp;int mtuoi;
  p1t=p1=phead;
  //pt truoc p,p1t truoc p1
  while(p1!=NULL)
   {pt=p1t;
    p=p1;
    p2t=p1;
    p2=p1->next;
    while(p2!=NULL)
     {if(p2->tuoi<p->tuoi) {pt=p2t;p=p2;}
      p2t=p2;
      p2=p2->next;
     }
    if(p==p1)
     {p1t=p1;
      p1=p1->next;
      continue;
     }
    if(p1==phead)
     {if(p1->next==p)//p va p1 lien nhau
    {ptmp=p->next;
     phead=p;p->next=p1;p1->next=ptmp;
    }
    else
    {ptmp=p->next;
     phead=p;p->next=p1->next;pt->next=p1;p1->next=ptmp;
    }
     }
     else
     {if(p1->next==p)//p va p1 lien nhau
    {ptmp=p->next;
     p1t->next=p;p->next=p1;p1->next=ptmp;
    }
    else
    {ptmp=p->next;
     p1t->next=p;p->next=p1->next;pt->next=p1;p1->next=ptmp;
    }
     }
    p1=p;
    p1t=p1;
    p1=p1->next;
   }
}

Vui lòng comment nội dung cần hỏi đáp cũng như trao đổi thêm

Tính thứ trong tuần sử dụng C

Đây là code viết bằng c, chúng ta cần nhập ngày tháng năm vào, chương trình sẽ đưa ra thứ tương ứng.

Chú ý : chương trình chỉ mang tính chất minh họa

#include <stdio.h>
#include <conio.h>
struct date
{
int month;
int day;
int year;
} date_1;

long int funct1 (int y,int m)
{
long int result;
if ( m <= 2 )
y -= 1;
result = y;
return (result);
}

long int funct2 (int m)
{
long int result;
if ( m <= 2 )
result = m + 13;
else
result = m + 1;
return(result);
}

long int day_count (int m, int d, int y)
{
long int number;
number = 1461 * funct1(y,m) / 4 + 153 * funct2(m) / 5 + d;

return (number);
}

void main ()
{
long int number_of_days1;
int day_of_week;

printf (“Nhap vao mot ngay (dd mm yyyy), vd 12 03 1999 \n”);
scanf (“%d %d %d”, &date_1.day, &date_1.month, &date_1.year);
number_of_days1 = day_count (date_1.month, date_1.day, date_1.year);
printf (“\nNgay la : ” );

day_of_week = (number_of_days1 – 621049) % 7;
switch (day_of_week)
{
case 0 :
printf (“Chu Nhat,”);
break;
case 1 :
printf (“Thu Hai,”);
break;
case 2 :
printf (“Thu Ba,”);
break;
case 3 :
printf (“Thu Tu,”);
break;
case 4 :
printf (“Thu Nam,”);
break;
case 5 :
printf (“Thu Sau,”);
break;
case 6 :
printf (“Thu Bay,”);
break;
}
getch();
}

Trim a string using C

#include <ctype.h>
#include <string.h>
#include <stdio.h>
#define NUL ”
char *trim(char *str)
{
      char *ibuf = str, *obuf = str;
      int i = 0, cnt = 0;
      if (str)
      {
           for (ibuf = str; *ibuf && isspace(*ibuf); ++ibuf);
            if (str != ibuf)
                  memmove(str, ibuf, ibuf – str);          
            while (*ibuf)
            {
                  if (isspace(*ibuf) && cnt)
                        ibuf++;
                  else
                  {
                        if (!isspace(*ibuf))
                              cnt = 0;
                        else
                        {
                              *ibuf = ‘ ‘;
                              cnt = 1;
                        }
                        obuf[i++] = *ibuf++;
                  }
            }
            obuf[i] = NUL;
            while (–i >= 0)
            {
                  if (!isspace(obuf[i]))
                        break;
            }
            obuf[++i] = NUL;
      }
      return str;
}
void main(int argc, char *argv[])
{
    char s[1000]="  Anh      yeu         em ";
      printf("trim(\"%s\") ", s);
      printf("returned \"%s\"\n", trim(s));
}

C or C++ Using the Windows API

C and C++ programs that use the Windows API functions consist of a main program, a window procedure, and possibly your own additional functions. The main program, which must be called WinMain(), sets up the window class (not to be confused with a C++ class), creates and initially displays the window, and manages the message loop. The window procedure, which will be called WindowProc() in all our examples, processes the messages it receives from Windows.

/****************************************************************************\
*                                                                            *
*  First.c                                                                   *
*                                                                            *
*  This is the first Fastgraph for Windows example program. It demonstrates  *
*  tasks common to most Fastgraph for Windows programs and serves as a       *
*  template for building the other examples.                                 *
*                                                                            *
\****************************************************************************/
#include <fgwin.h>
LRESULT CALLBACK WindowProc(HWND,UINT,WPARAM,LPARAM);
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PSTR szCmdParam, int iCmdShow)
{
   static char szAppName[] = "FGfirst";
   HWND        hWnd;
   MSG         msg;
   WNDCLASSEX  wndclass;
   wndclass.cbSize        = sizeof(wndclass);
   wndclass.style         = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
   wndclass.lpfnWndProc   = WindowProc;
   wndclass.cbClsExtra    = 0;
   wndclass.cbWndExtra    = 0;
   wndclass.hInstance     = hInstance;
   wndclass.hIcon         = LoadIcon(NULL,IDI_APPLICATION);
   wndclass.hCursor       = LoadCursor(NULL,IDC_ARROW);
   wndclass.hbrBackground = NULL;
   wndclass.lpszMenuName  = NULL;
   wndclass.lpszClassName = szAppName;
   wndclass.hIconSm       = LoadIcon(NULL,IDI_APPLICATION);
   RegisterClassEx(&wndclass);
   hWnd = CreateWindow(szAppName, // window class name
      "First Fastgraph for Windows Program", // window caption
      WS_OVERLAPPEDWINDOW,     // window style
      CW_USEDEFAULT,           // initial x position
      CW_USEDEFAULT,           // initial y position
      CW_USEDEFAULT,           // initial x size
      CW_USEDEFAULT,           // initial y size
      NULL,                    // parent window handle
      NULL,                    // window menu handle
      hInstance,               // program instance handle
      NULL);                   // creation parameters
   ShowWindow(hWnd,iCmdShow);
   UpdateWindow(hWnd);
   while (GetMessage(&msg,NULL,0,0))
   {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
   }
   return msg.wParam;
}
/****************************************************************************\
*                                                                            *
*  WindowProc                                                                *
*                                                                            *
*  Window procedure to handle messages sent to the window.                   *
*                                                                            *
\****************************************************************************/
HDC      hDC;
HPALETTE hPal;
int      hVB;
UINT     cxClient, cyClient;
LRESULT CALLBACK WindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
   PAINTSTRUCT ps;
   switch (iMsg)
   {
      case WM_CREATE:
         hDC = GetDC(hWnd);
         fg_setdc(hDC);
         hPal = fg_defpal();
         fg_realize(hPal);
         fg_vbinit();
         hVB = fg_vballoc(640,480);
         fg_vbopen(hVB);
         fg_vbcolors();
         fg_setcolor(19);
         fg_fillpage();
         return 0;
      case WM_PAINT:
         BeginPaint(hWnd,&ps);
         fg_vbscale(0,fg_getmaxx(),0,fg_getmaxy(),0,cxClient-1,0,cyClient-1);
         EndPaint(hWnd,&ps);
         return 0;
      case WM_SETFOCUS:
         fg_realize(hPal);
         InvalidateRect(hWnd,NULL,TRUE);
         return 0;
      case WM_SIZE:
         cxClient = LOWORD(lParam);
         cyClient = HIWORD(lParam);
         return 0;
      case WM_DESTROY:
         fg_vbclose();
         fg_vbfree(hVB);
         fg_vbfin();
         DeleteObject(hPal);
         ReleaseDC(hWnd,hDC);
         PostQuitMessage(0);
         return 0;
   }
   return DefWindowProc(hWnd,iMsg,wParam,lParam);
}

First, notice the directive at the beginning of the program:

#include <fgwin.h>

 

The FGWIN.H header file contains Fastgraph’s function prototypes and symbolic constant definitions. It also force-includes the WINDOWS.H header file if necessary. This statement will appear in the C and C++ versions of all Fastgraph example programs.

Now let’s look at WinMain(). WinMain() first sets up a window class that defines the window characteristics and associates a window procedure with the class. It then calls the CreateWindow() Windows API function to create a window based on that window class (this also generates the WM_CREATE message). CreateWindow() returns a window handle, which we store in the variable hWnd, for use elsewhere in the program. Next, the Windows API function ShowWindow() initially displays the window, and another Windows API function, UpdateWindow(), then generates the first WM_PAINT message to display the window contents. The remainder of WinMain() is a while loop implementing the message loop. The message loop retrieves messages Windows sends to the program and sends these to the program’s window procedure for processing. The message loop executes until the user exits the program. Note that we’ve exclusively used Windows API functions to handle the details of WinMain().

The window procedure WindowProc() is where most of the action takes place and provides our first look at some Fastgraph functions. Note that our program does not explicitly call WindowProc(). Instead, it is called by Windows in response to events such as creating or resizing the window. The message loop passes these events to WindowProc() as messages, which WindowProc() processes through its own distinct message handlers. WindowProc() implements the message handlers as a switch and case construct. Our window procedure includes WM_CREATE, WM_PAINT, WM_SETFOCUS, WM_SIZE, and WM_DESTROY message handlers, which we’ll now discuss in detail.

Windows generates a WM_CREATE message when it first creates the program’s window. Only one WM_CREATE message typically occurs per program instance, so it is a good place for any application-specific initialization code. Our WM_CREATE message handler first calls the Windows API function GetDC() to obtain a device context to the window’s client area and then calls fg_setdc() to make the device context available to other Fastgraph functions:

hDC = GetDC(hWnd);
fg_setdc(hDC);

 

Next, it creates and realizes the default logical palette:

hPal = fg_defpal();

fg_realize(hPal);

The WM_CREATE message handler then initializes Fastgraph’s virtual buffer environment, creates a 640×480 virtual buffer and makes it the active virtual buffer, and assigns the logical palette colors to the virtual buffer:

fg_vbinit();

hVB = fg_vballoc(640,480);

fg_vbopen(hVB);

fg_vbcolors();

Finally, we fill the virtual buffer with blue pixels (color 19 is blue when using Fastgraph’s default 256-color virtual buffers with the default logical palette):

fg_setcolor(19);

fg_fillpage();

Windows generates a WM_PAINT message when the window’s client area must be repainted. Our WM_PAINT handler begins with a call to the Windows API function BeginPaint(), then calls fg_vbscale() to display the contents of the 640×480 virtual buffer scaled to the size of the client area, and ends with a call to the Windows API function EndPaint(). This sequence is typical of WM_PAINT message handlers in Fastgraph programs.

Windows generates a WM_SETFOCUS message when the window gains the input focus. This most often happens when the window becomes the active or top-level window. Our WM_SETFOCUS handler first calls fg_realize() to activate the program’s logical palette (in case another program has changed the logical palette colors), then calls the Windows API function InvalidateRect() to force a WM_PAINT message to redraw the client area. This sequence is typical of WM_SETFOCUS message handlers in Fastgraph programs.

Windows generates a WM_SIZE message whenever the size of the window changes, and also upon creation of a window. Our WM_SIZE handler simply saves the new width and height of the client area (in pixels) in the variables cxClient and cyClient. These quantities are passed to fg_vbscale() in the WM_PAINT message handler.

Windows generates a WM_DESTROY message after removing a window to signal a program exit. Our WM_DESTROY handler first closes the virtual buffer, releases its memory, and terminates virtual buffer processing:

fg_vbclose();

fg_vbfree(hVB);

fg_vbfin();

It then calls three Windows API functions to delete the logical palette created with fg_defpal(), release the device context created with GetDC(), and exit:

DeleteObject(hPal);

ReleaseDC(hWnd,hDC);

PostQuitMessage(0);

Finally, our window procedure ends with a call to the Windows API function DefWindowProc(). This provides default message processing for the hundreds of other Windows message types not explicitly handled by the window procedure.

Source : fastgraph.com