考研數據結構之串(4.4)——練習題之實現串str的逆轉函數(C表示)

題目

實現串str的逆轉函數,如果str爲空串,則什麼都不做。

分析

由於串str是一個字符數組,所以逆轉字符串,即逆轉數組中的元素。

其實是個逆置問題

代碼

C語言代碼

void swap(char &c1,char &c2) {
	char temp=c1;
	c1=c2;
	c2=temp;
}

void invert(Str &str) {
	int i=0,j=str.length-1;
	while(i<j) {
		swap(str.ch[i],str.ch[j]);
		i++;
		j--;
	}
}

Java代碼

public class Demo1 {
    public static void main(String[] args) {
        String str="ABCDEFG";
        char[] chars = str.toCharArray();
        int i=0,j=chars.length-1;
        while (i<j){
            char temp=chars[i];
            chars[i]=chars[j];
            chars[j]=temp;
            i++;
            j--;
        }
        for (char aChar : chars) {
            System.out.print(aChar);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章